ComplianceServer/oldcode/Core.BLL/Application/Order/OrderService.cs

2807 lines
151 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using CRM.Core.BLL.B;
using CRM.Core.BLL.Base;
using CRM.Core.BLL.EventBus.Events;
using CRM.Core.BLL.Level2;
using CRM.Core.BLL.Mon;
using CRM.Core.BLL.Util;
using CRM.Core.BLL.Wx;
using CRM.Core.Common.WebHelper;
using CRM.Core.DTO;
using CRM.Core.DTO.Ord;
using CRM.Core.Model.Entity;
using CRM.Core.Model.Enum;
using CRM.Core.Model.QueryModels;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using WX.CRM.Common;
using WX.Interface.Security;
using static CRM.Core.BLL.Application.Order.ExportAudit;
namespace CRM.Core.BLL.Application.Order
{
public class OrderService
{
private static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
private WX_SZZYORDER_BL _order = new WX_SZZYORDER_BL();
private SecurityHelper sHelper = new SecurityHelper();
private WX_SzzyOrderPay_BL _orderPay = new WX_SzzyOrderPay_BL();
private BAS_PARAMETER_BL paramter_bl = new BAS_PARAMETER_BL();
private WX_PRODUCT_BL product_bl = new WX_PRODUCT_BL();
private L2_SOFT_ORDER_BL l2_soft_order_bl = new L2_SOFT_ORDER_BL();
private WX_OrderActive_BL orderActive_BL = new WX_OrderActive_BL();
private WX_SzzyOrderDeposit_BL _orderDeposit = new WX_SzzyOrderDeposit_BL();
private Module_Price_BL _modulePrice = new Module_Price_BL();
private Wx_SzzyOrderModuleRefund_BL _moduleRefund = new Wx_SzzyOrderModuleRefund_BL();
private Module_Order_Upgrad_BL _orderUpgrad = new Module_Order_Upgrad_BL();
private Wx_SzzyOrderPay_Ext_BL _orderPayExt = new Wx_SzzyOrderPay_Ext_BL();
private WX_SzzyOrderRefund_BL _refund = new WX_SzzyOrderRefund_BL();
private Wx_Order_PayClear_BL _payClear = new Wx_Order_PayClear_BL();
private readonly Wx_SzzyOrder_HandGift_BL _SzzyOrder_HandGift_BL = new Wx_SzzyOrder_HandGift_BL();
private Mon_Order_Act_BL _orderAct = new Mon_Order_Act_BL();
private Mon_Order_Income_BL _orderIncome = new Mon_Order_Income_BL();
private Mon_Order_Module_Act_BL _orderModuleAct = new Mon_Order_Module_Act_BL();
private Mon_Order_Module_Income_BL _orderModelIncome = new Mon_Order_Module_Income_BL();
private Dictionary<string, List<Mon_Order_Act>> _dic = new Dictionary<string, List<Mon_Order_Act>>();
private List<Mon_Order_Act> _monOrderActList = new List<Mon_Order_Act>();
private List<Mon_Order_Income> _monOrderIncome = new List<Mon_Order_Income>();
private Dictionary<string, List<Model.EntityAudit.Mon_Order_Module_Act>> _dic2 = new Dictionary<string, List<Model.EntityAudit.Mon_Order_Module_Act>>();
private List<Model.EntityAudit.Mon_Order_Module_Act> _monOrderModuleActList = new List<Model.EntityAudit.Mon_Order_Module_Act>();
private List<Model.EntityAudit.Mon_Order_Module_Income> _monOrderModuleIncome = new List<Model.EntityAudit.Mon_Order_Module_Income>();
//private static Dictionary<string, decimal> gyjList = new Dictionary<string, decimal>() { { "1011", 0 }, { "1012", 0 }, { "1028", 0 }, { "1018", 0 }, { "1082", 0 }, { "1010", 9800 }, { "1031", 20000 }, { "1038", 30000 }, { "1167", 30000 }, { "1162", 24000 }, { "1163", 24000 }, { "1183", 2800 }, { "1184", 2800 }, { "1185", 2800 }, { "100900118", 3980 }, { "100700614", 31572 }, { "100700616", 39800 }, { "100700605", 19800 } };
private Dictionary<string, decimal> gyjList = new Dictionary<string, decimal>();
//private static Dictionary<string, decimal> gyjList = new Dictionary<string, decimal>() { { "1011", 0 }, { "1012", 0 }, { "1028", 0 }, { "1018", 0 }, { "1082", 0 }, { "1010", 9800 }, { "1031", 20000 }, { "1038", 30000 }, { "1167", 30000 }, { "1162", 24000 }, { "1163", 24000 }, { "1183", 2800 }, { "1184", 2800 }, { "1185", 2800 }, { "1175", 3980 }, { "1181", 31572 }, { "1182", 39800 }, { "1099", 19800 } };
public retMsg Open(decimal orderId, int? operaid, string operaName)
{
try
{
var order = _order.GetModel(orderId);
if (order.ORDERSTATUS == "60")
{
return new retMsg { result = false, retcode = 60 };
}
//如果已经开通过,提示不能再开通了
if (order.ORDERSTATUS == "220")
{
return new retMsg { result = false, retcode = 220 };
}
//如果不是已支付状态,不能开通
if (!(order.ORDERSTATUS == "200"))
{
return new retMsg { result = false, retcode = 200 };
}
//如果不是风控通过状态,不能开通
//if (order.ARRIVALPAY >= 200)
//{
var product = product_bl.GetSubProduct(order.PRODUCTCODE);//获取产品信息,如果产品
if (product == null)
{
return new retMsg { result = false, retcode = 500, retmsg = "找不到订单对应产品" };
}
if (!product.needFK.HasValue || product.needFK.Value == 1)//设置了需要分控的产品订单,需要判断一下
{
if (order.RISKCTRLSTATUS == 0)
{
return new retMsg { result = false, retcode = 202, retmsg = "还未进行风控,请确认!" };
}
if (order.RISKCTRLSTATUS != 2)
{
return new retMsg { result = false, retcode = 201, retmsg = "风控未通过,请确认!" };
}
}
else//未进行风控的,但是没有签合同的,不能进行开通
{
if (product.isrealname == 1)
{
var parameter = paramter_bl.GetModel("Sys_nocontactcode_canopenorder");//没有签合同能否开通订单:1和null可以开通 0不能开通
if (parameter != null && parameter.PARAVALUE == "0" && string.IsNullOrEmpty(order.CONTRACTCODE))
{
return new retMsg { result = false, retcode = 500, retmsg = "没有签合同!" };
}
}
}
if (!string.IsNullOrEmpty(order.idcard))
{
if (_order.HasBlackList(order.idcard))
{
return new retMsg { result = false, retcode = 90, retmsg = "黑名单用户,禁止开通!" };
}
}
//}
//到账金额不能小于订单应付金额
if (order.ARRIVALPAY < order.NEEDPAY)
{
return new retMsg { result = false, retcode = 20 };
}
order.ORDERSTATUS = "220";
order.ORDERSTATUSNAME = "已开通";
order.ISOPEN = 1;
order.OTIME = DateTime.Now;
order.ENDTIME = order.OTIME.Value.AddDays(int.Parse(order.OPENDAYS.Value.ToString())); //结束日期
//非当期产品写入结算日期,当期单品需要使用交付日期做为结算日期
if (product.deliverType != 0)
{
if (!order.FINACEPAYDATE.HasValue)
{
order.ISFINANCEPAY = 1;
order.FINACEPAYDATE = order.OTIME;
}
}
//开通后 赋值 到款金额到 剩余金额
order.BALANCEPAY = order.ARRIVALPAY;
#region =================NodeJs开通订单========================
LogHelper.Info("====调用NodeJs开通订单===");
OpenOrderReq suorder = new OpenOrderReq();
suorder.orderId = order.SZZYORDERID.ToString();
suorder.businessOrderId = Convert.ToInt32(order.ORDERID);
Random rd = new Random();//用于生成随机数
string DateStr = DateTime.Now.ToString("yyyyMMddHHmmssfffffff");//日期
//string str = DateStr + rd.Next(10000).ToString().PadLeft(4, '0');//带日期的随机数
string str = "";//带日期的随机数
suorder.payType = order.PAYTYPE;
//从支付信息里面取最后审核过的一条记录如果支付流水是数字那么就取这条支付记录调用UP接口
//因为针对线上订单,开通的时候会推送支付信息个补单接口,支付流水号一致的情况,就不会写入重复的流水信息
var payInfoList = _orderPay.GetListByOrderId(Convert.ToInt32(order.ORDERID));
if (payInfoList != null && payInfoList.Count > 0)
{
//if (!Utility.IsChinese(payInfoList[0].payno))
//{
//str = payInfoList[0].payno;
str = payInfoList[0].payno + "_" + order.ORDERID;
suorder.payType = payInfoList[0].paytype;
//}
}
if (string.IsNullOrEmpty(str) && order.NEEDPAY > 0)
{
return new retMsg { result = false, retcode = 500, retmsg = "没有支付流水!" };
}
if (string.IsNullOrEmpty(str) && order.NEEDPAY == 0)//无流水的创造一个流水
{
Random random = new Random();
str = random.Next(1000000, 2000000) + "_" + order.ORDERID;
}
suorder.payId = str;//先随机生成
suorder.payPrice = Convert.ToInt32(order.NEEDPAY.Value * 100);
suorder.userName = order.SOFTUSERNAME;
suorder.isFree = 0;
if (order.NEEDPAY.Value == 0)
{
suorder.isFree = 1;
}
suorder.payRemark = "";//支付备注
var orderInfo = _order.GetStOrderInfo(order.ORDERID);
if (orderInfo != null)
{
suorder.sceneType = orderInfo.sceneType;
}
suorder.eid = order.eid;
//string json = string.Format("content={0}&clientid={1}&sign={2}", content, clientid, sign);//信息转发
string url = paramter_bl.GetValue_Parameter(Parameter.UserCenter_RiaService_OpenOrder);//封装出来的接口
string json = JsonHelper.ObjDivertToJson(suorder);
LogHelper.Info("Node.JS接口参数json=>:" + json);
json = JsonHelper.ObjDivertToJson(sHelper.createAjaxSignEncodingStr(json, SecurityHelper.OrderClientIdKey));
string retmsg = Utility.PostAjaxData(url, json, Encoding.UTF8);//返回信息
LogHelper.Info("Node.JS接口返回数据json=>:" + retmsg);
#endregion =================NodeJs开通订单========================
//retmsg = sHelper.decyptData(SecurityHelper.OrderClientIdKey, retmsg);
OpenOrderRsp retmessage = JsonHelper.JsonDivertToObj<OpenOrderRsp>(retmsg);
if (retmessage.retCode == (int)NodeJsOrderEnum.)//开通成功
{
//根据客户签约姓名更新订单用户名
var cName = retmessage.retMsg;
if (!string.IsNullOrWhiteSpace(cName) && cName != "Success")
{
if (cName.Contains('|'))
{
var arr = cName.Split('|');
order.CNAME = arr[0];
order.idcard = arr[1];
}
else
{
order.CNAME = cName;
}
}
//_order.Update(order);
_order.Update(order, x => new
{
x.ORDERSTATUS,
x.ORDERSTATUSNAME,
x.ISOPEN,
x.OTIME,
x.ENDTIME,
x.BALANCEPAY,
x.CNAME,
x.idcard,
x.ISFINANCEPAY,
x.FINACEPAYDATE
});//进行修改操作
//插入订单变更日志
_order.InserWxOrderLog(order.ORDERID);
//OpenOrderEventExec(order.ORDERID, order.ORDERSTATUS, order.ORDERSTATUSNAME, order.OTIME.Value, order.ENDTIME.Value, order.companycode, order.activeproductcode, order.activeproductext, order.CNAME, order.RESID, operaid, operaName);
var orderSubProduct = product_bl.GetSubProduct(order.PRODUCTCODE);
//如果是升级单,并且填写了升级单号则关闭对应的订单号
if (order.ORDERTYPE == 3)
{
if (!string.IsNullOrEmpty(order.UPGRADEORDERIDS))
{
var upgradeOrderList = order.UPGRADEORDERIDS.Split(',').Select(m => Convert.ToDecimal(m)).ToList();
foreach (var orderid in upgradeOrderList)
{
var oldOrder = _order.Get(p => p.ORDERID == orderid);
if (oldOrder != null)
{
//如果渠道产品的属性存在,用渠道产品的属性覆盖现有属性
var orderSubProductCH = product_bl.GetSzzySubProductChInfo(orderSubProduct.SUBPRODUCTID, order.CHANNEL);
if (orderSubProductCH != null)
{
orderSubProduct.Category = orderSubProductCH.category;
orderSubProduct.CloseUpgradeRole = orderSubProductCH.closeupgraderole;
}
var oldOrderSubProduct = product_bl.GetSubProduct(oldOrder.PRODUCTCODE);
//如果渠道产品的属性存在,用渠道产品的属性覆盖现有属性
var oldOrderSubProductCH = product_bl.GetSzzySubProductChInfo(oldOrderSubProduct.SUBPRODUCTID, oldOrder.CHANNEL);
if (oldOrderSubProductCH != null)
{
oldOrderSubProduct.CanUpgrade = oldOrderSubProductCH.canupgrade.Value;
oldOrderSubProduct.Category = oldOrderSubProductCH.category;
}
//只有当被升级的订单也是可以升级的订单,也就是说投顾产品之间互相升级,这种才会关闭原来订单
//如果是从非投顾产品补差价升级到投顾产品,原订单的权限不关闭
//如果升级的产品和原来的产品的分类Category相同那么也会执行关闭旧订单操作
//如果产品设置成需要关系被升级订单的权限
if ((oldOrderSubProduct != null && oldOrderSubProduct.CanUpgrade == 1) || (oldOrderSubProduct != null && orderSubProduct != null && orderSubProduct.Category == oldOrderSubProduct.Category) || (orderSubProduct.CloseUpgradeRole.HasValue && orderSubProduct.CloseUpgradeRole == 1))
{
#region =================NodeJs关闭订单========================
LogHelper.Info("====调用NodeJs关闭订单===");
freeOrderClose suorder2 = new freeOrderClose
{
userName = oldOrder.SOFTUSERNAME,
flag = "2",
orderId = oldOrder.SZZYORDERID.ToString()
};
var url2 = paramter_bl.GetValue_Parameter(Parameter.UserCenter_RiaService_closeFreeOrder);//封装出来的接口
var json2 = JsonHelper.ObjDivertToJson(suorder2);
LogHelper.Info("Node.JS接口参数json=>:" + json2);
var param2 = JsonHelper.ObjDivertToJson(sHelper.createAjaxSignEncodingStr(json2, SecurityHelper.OrderClientIdKey));
string retmsg2 = Utility.PostAjaxData(url2, param2, Encoding.UTF8);//返回信息
LogHelper.Info("Node.JS接口返回数据json=>:" + retmsg2);
freeOrderCloseRes retmessage2 = JsonHelper.JsonDivertToObj<freeOrderCloseRes>(retmsg2);
//关闭订单成功,本地被升级的订单更新成已升级状态
if (retmessage2.iRet == 0)
{
oldOrder.ORDERSTATUS = "205";
oldOrder.ORDERSTATUSNAME = "已升级";
_order.Update(oldOrder);
Common.EventBus.EventBus.Instance.Publish(new UpGradeOrderEvent(Convert.ToInt32(oldOrder.ORDERID), oldOrder.ORDERSTATUS, oldOrder.ORDERSTATUSNAME, oldOrder.companycode));
#region
if (!string.IsNullOrEmpty(oldOrder.activeproductext))
{
#region 退
var activeProductExt = Utility.JSONToObject<List<ActiveProduct>>(oldOrder.activeproductext);
//activeProductExt.Reverse();
var i = 0;
foreach (var item in activeProductExt)
{
var refundReq = new freeOrderClose { userName = order.SOFTUSERNAME, orderId = item.SzzyOrderId.ToString(), flag = "2" };
var param = JsonHelper.ObjDivertToJson(sHelper.createAjaxSignEncodingStr(JsonHelper.ObjDivertToJson(refundReq), SecurityHelper.OrderClientIdKey));
var refundRet = Utility.PostAjaxData(url2, param, Encoding.UTF8);
var refundRetMsg = JsonHelper.JsonDivertToObj<freeOrderCloseRes>(refundRet);
if (refundRetMsg.iRet == 0)
{
i++;
}
else
{
LogHelper.Error("执行升级单--赠送订单关闭失败:参数:" + refundRet + "--执行结果:+" + refundRet);
}
}
#endregion 退
}
//手工赠送订单退款
var handgiftOrder = _SzzyOrder_HandGift_BL.GetList(order.ORDERID);
//var handgiftOrdercount = handgiftOrder.Count();
foreach (var item in handgiftOrder)
{
//审核通过后才有权限id
if (item.orderstatus == 1 && item.szzyorderid.HasValue)
{
item.orderstatus = 3;
item.closememo = "升级关闭";
item.closetime = DateTime.Now;
item.closeuser = string.Format("{0}-{1}", operaid, operaName);
var refundReq = new freeOrderClose { userName = order.SOFTUSERNAME, orderId = item.szzyorderid.ToString(), flag = "0" };
var param = JsonHelper.ObjDivertToJson(sHelper.createAjaxSignEncodingStr(JsonHelper.ObjDivertToJson(refundReq), SecurityHelper.OrderClientIdKey));
var refundRet = Utility.PostAjaxData(url2, param, Encoding.UTF8);
var refundRetMsg = JsonHelper.JsonDivertToObj<freeOrderCloseRes>(refundRet);
if (refundRetMsg.iRet == 0)
{
_SzzyOrder_HandGift_BL.CheckGift(item);
Common.EventBus.EventBus.Instance.Publish(new HandGiftEvent(item, item.companycode));//推送数据到坐席端
}
else
{
LogHelper.Error("执行退款--手工赠送订单关闭失败:参数:" + refundRet + "--执行结果:+" + refundRet);
}
}
}
//插入订单变更日志
_order.InserWxOrderLog(order.ORDERID);
#endregion
}
#endregion =================NodeJs关闭订单========================
}
}
}
}
}
#region ===================
if ((order.giftdays.HasValue && order.giftdays > 0) || (order.giftdays2.HasValue && order.giftdays2 > 0))
{
try
{
//查询符合条件的活动信息
var orderCdate = DateTime.Now.Date;
if (order.CTIME.HasValue)
{
orderCdate = order.CTIME.Value.Date;
}
var activeList = orderActive_BL.GetList(order.PRODUCTCODE, order.companycode, orderCdate);
if (activeList != null && activeList.Count > 0)
{
string activeproductcode = "";
List<ActiveProduct> activeProductList = new List<ActiveProduct>();
foreach (var active in activeList)
{
//订购的数量达到最低要求
if (order.BOOKNUM >= active.MinCount)
{
var count = 0;//产品数量
//是否跟随订单赠送1用订单表的giftdays字段作为赠送时长0用本表的donateday字段作为赠送时长,2:用订单表的giftdays2字段作为赠送时长
if (active.IsFollowOrder == 1 && order.giftdays > 0)
{
count = order.BOOKNUM * order.giftdays.Value; //赠送天数,目前赠送天数以坐席端选择的赠送为准,不从活动表获取了
}
else if (active.IsFollowOrder == 2 && order.giftdays2 > 0)
{
count = order.BOOKNUM * order.giftdays2.Value; //赠送天数,目前赠送天数以坐席端选择的赠送为准,不从活动表获取了
}
else if (active.IsFollowOrder == 0 && order.giftdays > 0)
{
count = order.BOOKNUM * active.DonateDay;//产品数量
}
//如果赠送为0那么就跳过这个赠送产品执行下一个赠送产品
if (count == 0)
{
continue;
}
////ActiveType字段现在已经没用了数据库统一设置成1
//if (active.ActiveType == 2)
//{
// var opendays = order.OPENDAYS ?? 0;
// count = Convert.ToInt32(opendays) + order.BOOKNUM * active.DonateDay;
//}
#region =================NodeJs创建订单========================
LogHelper.Info("====调用NodeJs创建活动订单===");
//int channel = 0;
//int.TryParse(order.CHANNEL, out channel);
CreateOrderReq freeorder = new CreateOrderReq();
freeorder.productId = active.ActiveCode;
freeorder.userName = order.SOFTUSERNAME;
freeorder.count = count;//产品数量
freeorder.busType = 1;//
freeorder.ch = order.CHANNEL;
freeorder.source = 1;
freeorder.productType = active.ProductType;//0-单一产品、1-组合产品
freeorder.totalPrice = 0;
freeorder.cssId = order.INNERUSERID.ToString();
freeorder.currentCH = order.CHANNEL;
freeorder.ip = WX.CRM.Common.Utility.GetIp();//获取客户端IP
//freeorder.ip = string.Empty;
//string json = string.Format("content={0}&clientid={1}&sign={2}", content, clientid, sign);//信息转发
url = paramter_bl.GetValue_Parameter(Parameter.UserCenter_RiaService_AddOrderOpenFree);//封装出来的接口
string freejson = JsonHelper.ObjDivertToJson(freeorder);
LogHelper.Info("OpenFreeOrder=>Node.JS接口参数json=>:" + freejson);
freejson = JsonHelper.ObjDivertToJson(sHelper.createAjaxSignEncodingStr(JsonHelper.ObjDivertToJson(freeorder), SecurityHelper.OrderClientIdKey));
string freeretmsg = Utility.PostAjaxData(url, freejson, Encoding.UTF8);//返回信息
LogHelper.Info("OpenFreeOrder=>Node.JS接口返回数据json=>:" + freeretmsg);
//retmsg = sHelper.decyptData(SecurityHelper.OrderClientIdKey, retmsg);
CreateOrderRsp freeres = JsonHelper.JsonDivertToObj<CreateOrderRsp>(freeretmsg);
//======================================================================
#endregion =================NodeJs创建订单========================
if (freeres.retCode == (int)NodeJsOrderEnum.)
{
activeproductcode += active.ActiveCode + ",";
activeProductList.Add(new ActiveProduct { ActiveProductCode = active.ActiveCode, ActiveProductName = active.ProductName, DonateDay = count.ToString(), SzzyOrderId = Convert.ToInt64(freeres.orderId) });
L2_SOFT_ORDER model = new L2_SOFT_ORDER();
model.ORDERSTATUS = 1;
model.OPENUSER = order.INNERUSERID;
model.OTIME = DateTime.Now;
model.WEBORDERID = freeres.orderId;
model.PRODUCTID = active.ProductId;
model.PRODUCTCODE = active.ActiveCode;
model.RESID = order.RESID;
model.USERNAME = order.SOFTUSERNAME;
model.COMPANYID = order.SALEDEPTID;
model.CREATEUSER = order.INNERUSERID.Value;
model.ORDERTYPE = 1;
model.DAYS = count;
model.PRICE = 0;
model.CTIME = DateTime.Now;
model.companycode = order.companycode;
model.MainOrderId = Convert.ToInt32(order.ORDERID);
model.deptName = order.deptName;
model.deptid = order.deptid;
model.groupid = order.groupid;
model.sourcetype = 1;//订单开通
bool result = l2_soft_order_bl.OpenOrder(model);
//retmessage.selfOirderId = model.ORDERID.ToString();
}
else
{
LogHelper.Error("retmessage:" + freeretmsg);//记录下单不成功
}
}
}
if (!string.IsNullOrWhiteSpace(activeproductcode))
{
order.activeproductcode = activeproductcode.Trim(',');
order.activeproductext = JsonHelper.ObjDivertToJson(activeProductList);
_order.Update(order, x => new
{
x.activeproductcode,
x.activeproductext
});//进行修改操作
//OpenOrderEventExec(order.ORDERID, order.ORDERSTATUS, order.ORDERSTATUSNAME, order.OTIME.Value, order.ENDTIME.Value, order.companycode, order.activeproductcode, order.activeproductext, order.CNAME, order.RESID, operaid, operaName);
}
}
}
catch (Exception ex)
{
LogHelper.Error($"调用免费订单赠送不成功{order.ORDERID}{ex.Message}");
}
}
#endregion ===================
OpenOrderEventExec(order.ORDERID, order.ORDERSTATUS, order.ORDERSTATUSNAME, order.OTIME.Value, order.ENDTIME.Value, order.companycode, order.activeproductcode, order.activeproductext, order.CNAME, order.RESID, operaid, operaName);
try
{
#region
//var orderDeposit = _orderDeposit.GetList(p => p.orderid == order.ORDERID);
//if (orderDeposit.Any())
//{
// foreach (var item in orderDeposit)
// {
// item.isuse = -1;
// _orderDeposit.Update(item);
// //执行更新订金状态事件
// Common.EventBus.EventBus.Instance.Publish(new DepositUseOrderEvent(item.id, item.isuse, item.companycode));
// }
//}
#endregion
#region
var donateDays = string.Empty;
if (!string.IsNullOrEmpty(order.activeproductext))
{
var activeProduct = JsonHelper.JsonDivertToObj<List<ActiveProduct>>(order.activeproductext);
if (activeProduct != null)
{
donateDays = activeProduct.First().DonateDay;
}
//if (activeProduct.Count > 1)
//{
// var activeSubProduct = activeProduct.First(p => p.ActiveProductCode == order.activeproductcode);
// if (activeSubProduct != null)
// {
// donateDays = activeSubProduct.DonateDay;
// }
// else
// {
// donateDays = activeProduct.First().DonateDay;
// }
//}
//else
//{
// donateDays = activeProduct.First().DonateDay;
//}
}
OpenOrderSendSmsExec(int.Parse(order.ORDERID.ToString()), order.SOFTUSERNAME, order.SUBPRODUCTNAME, order.OPENDAYS.ToString(), donateDays, order.RESID);
#endregion
}
catch (Exception ex)
{
LogHelper.Error("发送短信失败:" + ex.ToString());
}
//推送开通订单到所有营业点
//Common.EventBus.EventBus.Instance.Publish(new AllOpenOrderEvent(order));
return new retMsg { result = true };
}
else if (retmessage.retCode == (int)NodeJsOrderEnum.)//已经开通过
{
//if (order.ORDERSTATUS != "220")
//{
LogHelper.Info("订单已经开通更新状态:" + order.ToJson());
_order.Update(order, x => new
{
x.ORDERSTATUS,
x.ORDERSTATUSNAME,
x.ISOPEN,
x.OTIME,
x.ENDTIME,
x.BALANCEPAY,
x.CNAME,
x.idcard,
x.ISFINANCEPAY,
x.FINACEPAYDATE
});//进行修改操作
OpenOrderEventExec(order.ORDERID, order.ORDERSTATUS, order.ORDERSTATUSNAME, order.OTIME.Value, order.ENDTIME.Value, order.companycode, order.activeproductcode, order.activeproductext, string.Empty, order.RESID, operaid, operaName);
//推送开通订单到所有营业点
Common.EventBus.EventBus.Instance.Publish(new AllOpenOrderEvent(order));
//}
return new retMsg { result = false, retmsg = "已经开通过了" };
}
else
{
return new retMsg { result = false, retmsg = string.IsNullOrEmpty(retmessage.retMsg) ? Utility.GetCheckEnumNameByValue<NodeJsOrderEnum>(retmessage.retCode) : retmessage.retMsg };
}
//======================================================================
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString());
return new retMsg { result = false, retmsg = ex.ToString() };
}
}
/// <summary>
/// 如果订单开通了,但是赠送没有赠送成功,那么需要这个方法来补充赠送
/// </summary>
public retMsg SuperOrderGif(decimal orderId)
{
try
{
var order = _order.GetModel(orderId);
//如果已经开通过,提示不能再开通了
if (order.ORDERSTATUS != "220")
{
return new retMsg { result = false, retcode = 220, retmsg = "只有已开通的订单才能够进行补充" };
}
if (!string.IsNullOrEmpty(order.activeproductext))
{
return new retMsg { result = false, retcode = 220, retmsg = "此订单赠送已经是赠送成功的,不能再次赠送" };
}
#region ===================
if ((order.giftdays.HasValue && order.giftdays > 0) || (order.giftdays2.HasValue && order.giftdays2 > 0))
{
try
{
//查询符合条件的活动信息
var orderCdate = DateTime.Now.Date;
if (order.CTIME.HasValue)
{
orderCdate = order.CTIME.Value.Date;
}
var activeList = orderActive_BL.GetList(order.PRODUCTCODE, order.companycode, orderCdate);
if (activeList != null && activeList.Count > 0)
{
string activeproductcode = "";
List<ActiveProduct> activeProductList = new List<ActiveProduct>();
foreach (var active in activeList)
{
//订购的数量达到最低要求
if (order.BOOKNUM >= active.MinCount)
{
var count = 0;//产品数量
//是否跟随订单赠送1用订单表的giftdays字段作为赠送时长0用本表的donateday字段作为赠送时长,2:用订单表的giftdays2字段作为赠送时长
if (active.IsFollowOrder == 1 && order.giftdays > 0)
{
count = order.BOOKNUM * order.giftdays.Value; //赠送天数,目前赠送天数以坐席端选择的赠送为准,不从活动表获取了
}
else if (active.IsFollowOrder == 2 && order.giftdays2 > 0)
{
count = order.BOOKNUM * order.giftdays2.Value; //赠送天数,目前赠送天数以坐席端选择的赠送为准,不从活动表获取了
}
else if (active.IsFollowOrder == 0 && order.giftdays > 0)
{
count = order.BOOKNUM * active.DonateDay;//产品数量
}
//如果赠送为0那么就跳过这个赠送产品执行下一个赠送产品
if (count == 0)
{
continue;
}
#region =================NodeJs创建订单========================
LogHelper.Info("====补调用NodeJs创建活动订单===");
CreateOrderReq freeorder = new CreateOrderReq();
freeorder.productId = active.ActiveCode;
freeorder.userName = order.SOFTUSERNAME;
freeorder.count = count;//产品数量
freeorder.busType = 1;//
freeorder.ch = order.CHANNEL;
freeorder.source = 1;
freeorder.productType = active.ProductType;//0-单一产品、1-组合产品
freeorder.totalPrice = 0;
freeorder.cssId = order.INNERUSERID.ToString();
freeorder.currentCH = order.CHANNEL;
freeorder.ip = WX.CRM.Common.Utility.GetIp();//获取客户端IP
//freeorder.ip = string.Empty;
if (freeorder.ip == "::1")
{
freeorder.ip = "127.0.0.1";
}
var url = paramter_bl.GetValue_Parameter(Parameter.UserCenter_RiaService_AddOrderOpenFree);//封装出来的接口
string freejson = JsonHelper.ObjDivertToJson(freeorder);
LogHelper.Info("补OpenFreeOrder=>Node.JS接口参数json=>:" + freejson);
freejson = JsonHelper.ObjDivertToJson(sHelper.createAjaxSignEncodingStr(JsonHelper.ObjDivertToJson(freeorder), SecurityHelper.OrderClientIdKey));
string freeretmsg = Utility.PostAjaxData(url, freejson, Encoding.UTF8);//返回信息
LogHelper.Info("补OpenFreeOrder=>Node.JS接口返回数据json=>:" + freeretmsg);
CreateOrderRsp freeres = JsonHelper.JsonDivertToObj<CreateOrderRsp>(freeretmsg);
//======================================================================
#endregion =================NodeJs创建订单========================
if (freeres.retCode == (int)NodeJsOrderEnum.)
{
activeproductcode += active.ActiveCode + ",";
activeProductList.Add(new ActiveProduct { ActiveProductCode = active.ActiveCode, ActiveProductName = active.ProductName, DonateDay = count.ToString(), SzzyOrderId = Convert.ToInt64(freeres.orderId) });
L2_SOFT_ORDER model = new L2_SOFT_ORDER();
model.ORDERSTATUS = 1;
model.OPENUSER = order.INNERUSERID;
model.OTIME = DateTime.Now;
model.WEBORDERID = freeres.orderId;
model.PRODUCTID = active.ProductId;
model.PRODUCTCODE = active.ActiveCode;
model.RESID = order.RESID;
model.USERNAME = order.SOFTUSERNAME;
model.COMPANYID = order.SALEDEPTID;
model.CREATEUSER = order.INNERUSERID.Value;
model.ORDERTYPE = 1;
model.DAYS = count;
model.PRICE = 0;
model.CTIME = DateTime.Now;
model.companycode = order.companycode;
model.MainOrderId = Convert.ToInt32(order.ORDERID);
model.deptName = order.deptName;
model.deptid = order.deptid;
model.groupid = order.groupid;
model.sourcetype = 1;//订单开通
bool result = l2_soft_order_bl.OpenOrder(model);
}
else
{
LogHelper.Error("retmessage:" + freeretmsg);//记录下单不成功
return new retMsg { result = false, retcode = 220, retmsg = "赠送失败:" + freeres.retMsg };
}
}
}
if (!string.IsNullOrWhiteSpace(activeproductcode))
{
order.activeproductcode = activeproductcode.Trim(',');
order.activeproductext = JsonHelper.ObjDivertToJson(activeProductList);
_order.Update(order, x => new
{
x.activeproductcode,
x.activeproductext
});//进行修改操作
}
}
}
catch (Exception ex)
{
LogHelper.Error($"补调用免费订单赠送不成功{order.ORDERID}{ex.Message}");
}
}
else
{
return new retMsg { result = false, retcode = 220, retmsg = "此订单没有需要赠送" };
}
#endregion ===================
return new retMsg { result = true };
}
catch (Exception ex)
{
LogHelper.Error(ex.ToString());
return new retMsg { result = false, retmsg = ex.ToString() };
}
}
/// <summary>
/// 判断是否可以进行开通
/// </summary>
public void CanIOpen(decimal orderId, int? operaid, string operaName)
{
try
{
var parameter = paramter_bl.GetModel("Sys_automatic_open");//是否开启自动开通订单功能:1开启 0和null没开启
if (parameter == null || parameter.PARAVALUE == "0")
{
return;//没开启自动开通功能
}
var orderinfo = _order.Get(m => m.ORDERID == orderId);
if (orderinfo == null)
return;//找不到订单,直接返回
if ((orderinfo.ORDERSTATUS == "200" || orderinfo.ORDERSTATUS == "201") && orderinfo.ARRIVALPAY == orderinfo.NEEDPAY)//如果已经支付了,和到账金额和需付金额一致,那么可以考虑下一步进行开通
{
var product = product_bl.GetSubProduct(orderinfo.PRODUCTCODE);
if (product == null)
return;//找不到产品
if (product.automaticOpen.HasValue && product.automaticOpen.Value == 0)
{
return;//关闭了自动开通
}
//产品配置必须实名才能开通
if (product.isrealname == 1)
{
if (string.IsNullOrEmpty(orderinfo.idcard) || string.IsNullOrEmpty(orderinfo.CNAME))//无姓名,无身份证,不能开通
{
return;
}
}
if (orderinfo.RISKCTRLSTATUS == 2 || (product.needFK.HasValue && product.needFK.Value == 0))//通过分控,或者产品设置了不需要风控也能进行开通
{
/*
estimateotime==null :直接开通
estimateotime<当前时间:进行开通
*/
DateTime nowtime = DateTime.Now;
if (!orderinfo.estimateotime.HasValue || orderinfo.estimateotime.Value < nowtime)//时间条件符合自动开通条件
{
Open(orderId, operaid, operaName);//调用开通
}
}
}
}
catch (Exception e)
{
LogHelper.Error("自动开通失败CanIOpen" + e.ToString());
}
}
/// <summary>
/// 订金使用,订金审核,调用本方法判断涉及的订单是否需要开通
/// </summary>
/// <param name="depositId"></param>
/// <param name="operaid"></param>
/// <param name="operaName"></param>
public void CanIOpenByDepositAuditOrUse(int[] depositIds, int? operaid, string operaName)
{
try
{
var parameter = paramter_bl.GetModel("Sys_automatic_open");//是否开启自动开通订单功能:1开启 0和null没开启
if (parameter == null || parameter.PARAVALUE == "0")
{
return;//没开启自动开通功能
}
int[] orderIds = _orderPay.GetOrderIdsByDepositIds(depositIds);
foreach (var id in orderIds)
{
CanIOpen(id, operaid, operaName);//循环判断是否需要开通订单
}
}
catch (Exception e)
{
LogHelper.Error("自动开通失败CanIOpenByDepositAuditOrUse" + e.ToString());
}
}
/// <summary>
/// 弃用,新方法见 WX_SzzyOrderDeposit_BL.OrderCancel
/// </summary>
/// <param name="orderId"></param>
/// <returns></returns>
public retMsg ReSet(int orderId)
{
try
{
var deposit = new WX_SzzyOrderDeposit_BL();
#region
var order = _order.GetModel(orderId);
//如果已经开通过,提示不能操作
if (order.ORDERSTATUS == "220")
{
return new retMsg { result = false, retcode = 220 };
}
order.ORDERSTATUS = "180";
order.ORDERSTATUSNAME = "新订单";
order.ARRIVALPAY = null;
order.ARRIVALTIME = null;
_order.Update(order);
var orderDeposit = _orderDeposit.GetList(p => p.orderid == order.ORDERID);
foreach (var item in orderDeposit)
{
item.isuse = 0;
item.orderid = null;
_orderDeposit.Update(item);
}
var payInfoList = _orderPay.GetListByOrderId(Convert.ToInt32(order.ORDERID));
foreach (var item in payInfoList)
{
var djInfo = orderDeposit.FirstOrDefault(p => p.payno == item.payno);
if (djInfo != null)
{
item.orderid = djInfo.id;
}
else
{
item.auditstatus = 0;
item.isdelete = 1;
}
_orderPay.Update(item);
}
Common.EventBus.EventBus.Instance.Publish(new ReSetOrderEvent(orderId, order.CHANNEL));
#endregion
}
catch (Exception e)
{
LogHelper.Error(e);
return new retMsg { result = false };
}
return new retMsg { result = true };
}
#region
/// <summary>
/// 清除数据,重新结算
/// </summary>
/// <param name="sTime"></param>
/// <param name="eTime"></param>
/// <param name="bTime"></param>
/// <param name="fTime"></param>
/// <param name="channel"></param>
/// <returns></returns>
public retMsg FlushExecInomce(DateTime sTime, DateTime eTime, DateTime? bTime, DateTime? fTime, string channel)
{
//清除结算数据
_orderModelIncome.FlushIncome();
return ExecInomce(sTime, eTime, bTime, fTime, channel);
}
/// <summary>
/// 收入结算
/// </summary>
/// <param name="sTime"></param>
/// <param name="eTime"></param>
/// <param name="bTime"></param>
/// <param name="fTime"></param>
/// <param name="channel"></param>
public retMsg ExecInomce(DateTime sTime, DateTime eTime, DateTime? bTime, DateTime? fTime, string channel)
{
var check = _orderModelIncome.Check(int.Parse(bTime.Value.ToString("yyyyMM")));
if (!check)
{
return new retMsg { result = false, retcode = 100, retmsg = "已经结算过了" };
}
ExecOrderModelAct(sTime, eTime, bTime, fTime, channel);
if (_monOrderModuleActList.Any())
{
//之前未处理的数据,已经加载处理,所以之前的数据做删除操作
var ret = _orderModuleAct.Delete(p => p.Status == 0);
if (ret)
{
_orderModuleAct.BulkInsertToMysql("Mon_Order_Module_Act", _monOrderModuleActList);
////_orderModelIncome.BulkInsertToMysql("Mon_Order_Module_Income", _monOrderModuleIncome);
_orderModelIncome.ExeIncome();
_orderModelIncome.Finish(int.Parse(eTime.ToString("yyyyMM")), eTime);
}
}
ExecActYG(eTime.AddDays(1), eTime.AddYears(3), fTime.Value.AddYears(3), fTime.Value.AddYears(3), channel);
return new retMsg { result = true, retcode = 200, retmsg = "" };
}
/// <summary>
/// 收入结算预估
/// </summary>
/// <param name="sTime"></param>
/// <param name="eTime"></param>
/// <param name="bTime"></param>
/// <param name="fTime"></param>
/// <param name="channel"></param>
public void ExecActYG(DateTime sTime, DateTime eTime, DateTime? bTime, DateTime? fTime, string channel)
{
LogHelper.Info("sTime:" + sTime.ToString());
LogHelper.Info("eTime:" + eTime.ToString());
LogHelper.Info("bTime:" + bTime.Value.ToString());
LogHelper.Info("fTime:" + fTime.Value.ToString());
ExecOrderModelAct(sTime, eTime, bTime, fTime, channel);
if (_monOrderModuleActList.Any())
{
_orderModuleAct.InitDataYG();
_orderModuleAct.BulkInsertToMysql("mon_order_module_act_yg", _monOrderModuleActList);
}
}
/// <summary>
/// 当前预估
/// </summary>
/// <param name="sTime"></param>
/// <param name="eTime"></param>
/// <param name="bTime"></param>
/// <param name="fTime"></param>
/// <param name="channel"></param>
public void ExecActCur()
{
var finish = new Mon_Order_Module_Income_BL().GetLastFinish();
if (finish == null)
{
LogHelper.Info("未找到结算数据,请确认!");
return;
}
var btime = finish.Day.AddDays(1);
var ftime = Convert.ToDateTime(DateTime.Now.ToShortDateString()).AddDays(-1);
var stime = btime;
var etime = finish.Day.AddYears(3).AddMonths(1);
Logger.Info("ExecActCur结算入参stime=" + stime.ToString() + ",etime=" + etime.ToString() + ",btime=" + btime.ToString() + ",ftime=" + ftime.ToString());
ExecOrderModelAct(stime, etime, btime, ftime, string.Empty);
if (_monOrderModuleActList.Any())
{
_orderModuleAct.InitDataCur();
_orderModuleAct.BulkInsertToMysql("mon_order_module_act_cur", _monOrderModuleActList);
_orderModelIncome.UpdateDataEnd(int.Parse(finish.Day.ToString("yyyyMM")), ftime);
}
}
public void ExecOrderModelAct(DateTime sTime, DateTime eTime, DateTime? bTime, DateTime? fTime, string channel)
{
_dic2.Clear();
_monOrderModuleActList.Clear();
var omonth = int.Parse(sTime.ToString("yyyyMM"));
eTime = eTime.AddDays(1);
//需要有公允价的moduleId
var moduleIds = _modulePrice.GetModuleIds();
//公允价
gyjList = _order.GetFairPrice();
var unknownModuleIds = new List<string>();
foreach (var item in moduleIds)
{
if (!gyjList.Keys.Any(p => p == item))
{
unknownModuleIds.Add(item);
}
}
//订单数据
var orderList = _order.GetOpenOrderModule(sTime, eTime, bTime, fTime, channel);
//到账成本信息
var orderPayExtList = _order.GetPayList();
var orderPayExtKvList = orderPayExtList.ToDictionary(d => d.OrderId, d => d);
//升级订单数据
var upgradOrder = _orderUpgrad.GetList(p => p.isbeclose == 1);
var orderModelActList = _orderModuleAct.GetList(p => p.Status == 0).ToList();
foreach (var act in orderModelActList)
{
var actList = new List<Model.EntityAudit.Mon_Order_Module_Act>();
if (_dic2.ContainsKey(act.UserName))
{
_dic2.TryGetValue(act.UserName, out actList);
actList.Add(act);
}
else
{
actList.Add(act);
_dic2.Add(act.UserName, actList);
}
}
var diffDays = eTime.Subtract(sTime);
var odayList = orderList.GroupBy(d => d.acttime.Date).ToList();
Dictionary<DateTime, List<OrderModuleDto>> dayList = new Dictionary<DateTime, List<OrderModuleDto>>();
foreach (var item in odayList)
{
dayList.Add(item.Key.Date, item.ToList());
}
var dataCount = _orderModuleAct.Count();
//数据需要一天一天处理
for (int i = 0; i < diffDays.Days; i++)
{
var aTime = sTime.AddDays(1);
//var orders = orderList.Where(p => p.acttime >= sTime && p.acttime < aTime);
List<OrderModuleDto> orders = new List<OrderModuleDto>();
if (dayList.TryGetValue(sTime, out orders))
{
var orderIds = orders.GroupBy(p => new { p.orderid, p.username }).Select(p => p.Key);
LogHelper.Info(string.Format("开始执行{0}", sTime.ToString()));
foreach (var orderKey in orderIds)
{
if (sTime.ToString("yyyy-MM-dd") == "2022-07-31" && orderKey.orderid == 80459609)
{
var a = 0;
}
if (sTime.ToString("yyyy-MM-dd") == "2020-12-03" && orderKey.orderid == 80149703)
{
}
//try
//{
var actList = new List<Model.EntityAudit.Mon_Order_Module_Act>();
var orderItem = orders.Where(p => p.orderid == orderKey.orderid && p.isrefund == 0);
var orderRefundItem = orders.Where(p => p.orderid == orderKey.orderid && p.isrefund == 1);
var unknownmoduleid = false;
foreach (var item in orderItem)
{
if (unknownModuleIds.Any(p => p == item.moduleid))
{
LogHelper.Info(item.moduleid + "未设置公允价:" + item.ToJson());
unknownmoduleid = true;
}
}
if (unknownmoduleid)
{
//未设置公允价的订单不要影响正常订单
continue;
}
//订单价格
//var orderPrice = orderItem.OrderByDescending(p => p.orderPrice).First().orderPrice;
// var orderPayInfo = orderPayExtList.FirstOrDefault(p => p.OrderId == orderKey.orderid);
var orderPayInfo = new Model.EntityAudit.Wx_SzzyOrderPay_Ext();
if (!orderPayExtKvList.TryGetValue(orderKey.orderid, out orderPayInfo))
//if (orderPayInfo == null)
{
LogHelper.Info(orderKey.orderid.ToString() + "价格为空:" + orderItem.ToJson());
throw new Exception(orderKey.orderid.ToString() + "价格为空: " + orderItem.ToJson());
}
var isFind = _dic2.TryGetValue(orderKey.username, out actList);
if (actList == null)
{
actList = new List<Model.EntityAudit.Mon_Order_Module_Act>();
_dic2.Add(orderKey.username, actList);
}
var isHis = false;
if (dataCount > 0)
{
isHis = _orderModuleAct.Exists(p => p.UserName == orderKey.username);
}
//var isHis = _orderModuleAct.Exists(p => p.UserName == orderKey.username);
if (!(isFind || isHis))
{
//var isHisFind = _orderModuleAct
//如果用户不存在
//新单
decimal totalPrice = orderPayInfo.PayPrice + 0;
decimal tfPrice = 0;
foreach (var order in orderItem)
{
//支付金额
var payPrice = JiSuanPrice(order, orderItem, orderPayInfo.PayPrice, 0);
//剩余金额
var actPrice = JiSuanPrice(order, orderItem, orderPayInfo.PayPrice, 0);
//订单金额
decimal orderPrice = 0;
//成本金额
decimal? costPrice = null;
//订单剩余金额
decimal lastOrderPrice = 0;
//剩余成本金额
decimal? lastCostPrice = null;
if (orderPayInfo.Rate.HasValue && orderPayInfo.Rate.Value > 0)
{
//orderPrice = actPrice * (1 - orderPayInfo.Rate.Value);
lastOrderPrice = actPrice * orderPayInfo.Rate.Value;
}
//else
//{
// orderPrice = actPrice;
//}
//消耗价值
var usePrice = 0;
//消耗时长
var useDayCount = 0;
//var useOrderPrice = 0;
//var useCostPrice = 0;
//上个状态剩余价值
var lastPrice = 0;
//上个状态剩余时长
var lastDayCount = 0;
//var lastOrderPrice = 0;
//var lastCostPrice = lastOrderPrice;
var orderCount = order.opendays.Value;
var dayCount = order.opendays.Value;
//记收入跟预收
decimal income = 0;
decimal depositreceived = 0;
actList.Add(new Model.EntityAudit.Mon_Order_Module_Act(Guid.NewGuid().ToString(), order.stime, order.username, order.moduleid, lastPrice, usePrice, payPrice, actPrice, lastDayCount, useDayCount, orderCount, dayCount, order.orderid, sTime, "新订单", order.otime, order.channel, orderPrice, lastOrderPrice, costPrice, lastCostPrice, orderPayInfo.Rate, income, depositreceived, null));
tfPrice += (actPrice + income);
}
if (totalPrice.ToString("#0.00") != tfPrice.ToString("#0.00"))
{
LogHelper.Info("新订单摊分金额错误totalPrice" + totalPrice.ToString() + "tfPrice" + tfPrice.ToString() + "---" + orderItem.ToJson());
//throw new Exception("error");
}
//_dic2.Add(orderKey.username, actList);
}
else
{
var isExists = actList.Any(p => p.OrderId == orderKey.orderid);
var isExistsAct = false;
if (dataCount > 0)
{
isExistsAct = _orderModuleAct.Exists(p => p.OrderId == orderKey.orderid);
}
//var isExistsAct = _orderModuleAct.Exists(p => p.OrderId == orderKey.orderid);
if (!(isExists || isExistsAct))
{
//不存在订单,说明是有价订单
//升级单
var upOrders = upgradOrder.Where(p => p.new_orderid == orderKey.orderid).ToList();
if (upOrders.Any())
{
//升级单
decimal shengyuPayPrice = 0;
decimal shengyuOrderPrice = 0;
//decimal shengyuCostPrice = 0;
foreach (var upOrder in upOrders)
{
//*****升级单消耗价值计算 begin********///
var lastOrders = actList.Where(p => p.OrderId == upOrder.old_orderid && p.ActDay < sTime && p.Status == 0).ToList();
foreach (var lastOrder in lastOrders)
{
//var lastModel = actList.Where(p => p.OrderId == upOrder.old_orderid && p.ModuleId == lastOrder.ModuleId && p.Status == 0).OrderBy(p=>p.ActDay).First();
var lastModel = lastOrder;
//更新原来的状态为已结
lastModel.Status = 1;
//消耗天数
var actDay = DateTime.Parse(lastModel.ActDay.ToShortDateString());
var ts = sTime.Subtract(actDay);
var useDay = ts.Days;
//结算时已过期,按剩余天数结算
if (useDay > lastModel.DayCount)
{
useDay = lastModel.DayCount;
}
//消耗价值
decimal usePrice = 0;
decimal orderPrice = 0;
//decimal costPrice = 0;
if (lastModel.DayCount > 0)
{
usePrice = lastModel.ActPrice / lastModel.DayCount * useDay;
orderPrice = lastModel.LastOrderPrice.Value / lastModel.DayCount * useDay;
//costPrice = lastModel.LastCostPrice.Value / lastModel.DayCount * useDay;
}
//支付金额
var payPrice = lastModel.ActPrice - usePrice;
//剩余金额
var actPrice = lastModel.ActPrice - usePrice;
//订单金额
var lastOrderPrice = lastModel.LastOrderPrice - orderPrice;
//成本金额
//var lastCostPrice = lastModel.LastCostPrice - costPrice;
var orderCount = lastModel.DayCount - useDay;
//剩余天数
var dayCount = lastModel.DayCount - useDay;
var lastPrice = lastModel.ActPrice;
var lastDayCount = lastModel.DayCount;
//记收入跟预收
decimal income = usePrice;
decimal depositreceived = 0;
//记成本跟剩余成本
decimal costPrice = orderPrice;
decimal lastCostPrice = 0;
//注意不是月结的结算数据,剩余价值不计,只计收入
//写入状态表
var guid = Guid.NewGuid().ToString();
actList.Add(new Model.EntityAudit.Mon_Order_Module_Act(guid, sTime, lastModel.UserName, lastModel.ModuleId, lastPrice, -usePrice, payPrice, actPrice, lastDayCount, useDay, orderCount, dayCount, lastModel.OrderId, sTime, "状态变化结算(升级单)", lastModel.OTime, lastModel.Channel, -orderPrice, lastOrderPrice, costPrice, lastCostPrice, lastModel.CostRate, income, depositreceived, int.Parse(sTime.ToString("yyyyMM"))) { FinishStatus = 0 });
//写入结算表
//_monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, sTime, 0, usePrice, 0, useDay, lastModel.OrderId, lastModel.OTime, lastModel.Channel, lastModel.UserName, useOrderPrice, 0, useCostPrice, 0));
}
//*****升级单消耗价值计算 end********///
//******获取剩余价值 begin**//
//重新获取一次,剩余价值做收入处理
lastOrders = actList.Where(p => p.OrderId == upOrder.old_orderid && p.Status == 0).ToList();
foreach (var lastOrder in lastOrders)
{
lastOrder.Status = 1;
//剩余天数
var orderCount = 0;
var dayCount = 0;
//剩余价值
var payPrice = 0;
var actPrice = 0;
decimal orderPrice = lastOrder.LastOrderPrice ?? 0;
decimal lastOrderPrice = 0;
//成本
//var costPrice = 0;
//剩余成本
//var lastCostPrice = -lastOrder.LastCostPrice;
//剩余价值
shengyuPayPrice += lastOrder.ActPrice;
shengyuOrderPrice += lastOrder.LastOrderPrice.Value;
//shengyuCostPrice += lastOrder.LastCostPrice ?? 0;
var lastPrice = lastOrder.ActPrice;
var lastDayCount = lastOrder.DayCount;
var usePrice = lastOrder.ActPrice;
var useDay = lastOrder.DayCount;
//记收入跟预收
decimal income = 0;
decimal depositreceived = -usePrice;
//记成本跟剩余成本
decimal costPrice = 0;
decimal lastCostPrice = -orderPrice;
var guid = Guid.NewGuid().ToString();
//写入状态表
var actModel = new Model.EntityAudit.Mon_Order_Module_Act(guid, lastOrder.ActDay, lastOrder.UserName, lastOrder.ModuleId, lastPrice, -usePrice, payPrice, actPrice, lastDayCount, useDay, orderCount, dayCount, lastOrder.OrderId, sTime, "被升级摊分", lastOrder.OTime, lastOrder.Channel, -orderPrice, lastOrderPrice, costPrice, lastCostPrice, lastOrder.CostRate, income, depositreceived, int.Parse(sTime.ToString("yyyyMM")))
{
Status = 1,
FinishStatus = 0
};
actList.Add(actModel);
//写入结算表
//_monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, sTime, 3, 0, -lastOrder.ActPrice, lastActPrice, lastOrder.OrderId, lastOrder.OTime, lastOrder.Channel, lastOrder.UserName, lastOrderPrice, -lastOrder.LastOrderPrice, lastCostPrice, -lastOrder.LastCostPrice));
}
/******获取剩余价值 end**/
}
//升级单
decimal totalPrice = orderPayInfo.PayPrice + shengyuPayPrice;
decimal tfPrice = 0;
foreach (var order in orderItem)
{
//支付金额
var payPrice = JiSuanPrice(order, orderItem, orderPayInfo.PayPrice, 0);
//剩余金额
var actPrice = JiSuanPrice(order, orderItem, orderPayInfo.PayPrice, 0);
//订单金额
decimal orderPrice = 0;
//成本金额
decimal? costPrice = null;
//订单剩余金额
decimal lastOrderPrice = 0;
//剩余成本金额
decimal? lastCostPrice = null;
if (orderPayInfo.Rate.HasValue && orderPayInfo.Rate.Value > 0)
{
//orderPrice = actPrice * (1 - orderPayInfo.Rate.Value);
lastOrderPrice = actPrice * orderPayInfo.Rate.Value;
}
//else
//{
// orderPrice = actPrice;
//}
//消耗价值
var usePrice = 0;
//消耗时长
var useDayCount = 0;
//var useOrderPrice = 0;
//var useCostPrice = 0;
//上个状态剩余价值
var lastPrice = 0;
//上个状态剩余时长
var lastDayCount = 0;
//var lastOrderPrice = 0;
//var lastCostPrice = 0;
var orderCount = order.opendays.Value;
var dayCount = order.opendays.Value;
//记收入跟预收
decimal income = 0;
decimal depositreceived = 0;
//写入升级单原始单
var actInfo = new Model.EntityAudit.Mon_Order_Module_Act(Guid.NewGuid().ToString(), order.stime, order.username, order.moduleid, lastPrice, usePrice, payPrice, actPrice, lastDayCount, useDayCount, orderCount, dayCount, order.orderid, sTime, "升级订单(新订单)", order.otime, order.channel, orderPrice, lastOrderPrice, costPrice, lastCostPrice, orderPayInfo.Rate, income, depositreceived, null)
{
Status = 1
};
actList.Add(actInfo);
//重算支付金额
var respayPrice = JiSuanPrice(order, orderItem, orderPayInfo.PayPrice, shengyuPayPrice);
var resmodulePrice = JiSuanPrice(order, orderItem, orderPayInfo.PayPrice, shengyuPayPrice);
//重算订单金额
decimal resorderPrice = JiSuanRatePirce(order, orderItem, orderPayInfo.PayPrice, shengyuPayPrice, orderPayInfo.OrderPrice + shengyuOrderPrice);
//重算成本金额
decimal rescostPrice = JiSuanRatePirce(order, orderItem, orderPayInfo.PayPrice, shengyuPayPrice, orderPayInfo.CostPrice + shengyuOrderPrice);
//***升级摊分的金额***//
var syPayPrice = respayPrice - payPrice;
var syModulePrice = resmodulePrice - actPrice;
var syOrderPrice = 0;
//var syLastOrderPrice = resorderPrice - orderPrice;
//var syCostPrice = rescostPrice - costPrice;
//记收入跟预收
decimal syIncome = 0;
decimal syDepositreceived = syModulePrice;
//记成本
decimal syCostPrice = 0;
decimal syLastCostPrice = rescostPrice - lastOrderPrice;
//LogHelper.Info("syCostPrice:" + syCostPrice.ToString() + "---syLastCostPrice:" + syLastCostPrice.ToString());
//写入结算表
//_monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, sTime, 3, 0, syModulePrice, 0, order.orderid, order.otime, order.channel, order.username, 0, syOrderPrice, 0, syCostPrice));
//更新成本比例
var fm = (shengyuPayPrice + orderPayInfo.PayPrice);
decimal rate = 0;
if (fm > 0)
{
rate = (shengyuOrderPrice + orderPayInfo.CostPrice) / fm;
}
//先结算,然后在写入升级单
actList.Add(new Model.EntityAudit.Mon_Order_Module_Act(Guid.NewGuid().ToString(), order.stime, order.username, order.moduleid, 0, 0, respayPrice, resmodulePrice, 0, 0, orderCount, dayCount, order.orderid, sTime, "升级订单", order.otime, order.channel, 0, rescostPrice, syCostPrice, syLastCostPrice, rate, syIncome, syDepositreceived, int.Parse(sTime.ToString("yyyyMM"))) { FinishStatus = 0 });
tfPrice += (resmodulePrice + syIncome);
}
if (totalPrice.ToString("#0.00") != tfPrice.ToString("#0.00"))
{
LogHelper.Info("升级订单摊分金额错误totalPrice" + totalPrice.ToString() + "tfPrice" + tfPrice.ToString() + "---" + orderItem.ToJson());
//throw new Exception("error");
//break;
}
//更新成本比例
//var fm = (shengyuPayPrice + orderPayInfo.PayPrice);
//decimal rate = 0;
//if (fm > 0)
//{
// rate = (shengyuCostPrice + orderPayInfo.CostPrice) / fm;
//}
//orderPayInfo.CostPrice = (shengyuCostPrice + orderPayInfo.CostPrice);
//orderPayInfo.Rate = rate;
}
else
{
//重新购买
decimal totalPrice = orderPayInfo.PayPrice + 0;
decimal tfPrice = 0;
foreach (var order in orderItem)
{
//支付金额
var payPrice = JiSuanPrice(order, orderItem, orderPayInfo.PayPrice, 0);
//剩余金额
var actPrice = JiSuanPrice(order, orderItem, orderPayInfo.PayPrice, 0);
//订单金额
decimal orderPrice = 0;
//成本金额
decimal? costPrice = null;
//订单剩余金额
decimal lastOrderPrice = 0;
//剩余成本金额
decimal? lastCostPrice = null;
if (orderPayInfo.Rate.HasValue && orderPayInfo.Rate.Value > 0)
{
//orderPrice = actPrice * (1 - orderPayInfo.Rate.Value);
lastOrderPrice = actPrice * orderPayInfo.Rate.Value;
}
//else
//{
// orderPrice = actPrice;
//}
//消耗价值
var usePrice = 0;
//消耗时长
var useDayCount = 0;
//var useOrderPrice = 0;
//var useCostPrice = 0;
//上个状态剩余价值
var lastPrice = 0;
//上个状态剩余时长
var lastDayCount = 0;
//var lastOrderPrice = 0;
//var lastCostPrice = 0;
var orderCount = order.opendays.Value;
var dayCount = order.opendays.Value;
//记收入跟预收
decimal income = 0;
decimal depositreceived = 0;
actList.Add(new Model.EntityAudit.Mon_Order_Module_Act(Guid.NewGuid().ToString(), order.stime, order.username, order.moduleid, lastPrice, usePrice, payPrice, actPrice, lastDayCount, useDayCount, orderCount, dayCount, order.orderid, sTime, "新订单2", order.otime, order.channel, orderPrice, lastOrderPrice, costPrice, lastCostPrice, orderPayInfo.Rate, income, depositreceived, null));
tfPrice += (actPrice + income);
}
if (totalPrice.ToString("#0.00") != tfPrice.ToString("#0.00"))
{
LogHelper.Info("新订单2摊分金额错误totalPrice" + totalPrice.ToString() + "tfPrice" + tfPrice.ToString() + "---" + orderItem.ToJson());
//throw new Exception("error");
}
}
}
else
{
//免费单
if (orderItem.Any())
{
//根据订单找到最后一条未结算信息
var lastOrder = actList.Where(p => p.OrderId == orderKey.orderid && p.ActDay < sTime && p.Status == 0).ToList();
/******计算消耗价值 begin********/
foreach (var lastModel in lastOrder)
{
//消耗天数
var actDay = DateTime.Parse(lastModel.ActDay.ToShortDateString());
var ts = sTime.Subtract(actDay);
var useDay = ts.Days;
//useDay <= 0 还没开始执行
if (useDay > 0)
{
//更新原来的状态为已结
lastModel.Status = 1;
}
//结算时已过期,按剩余天数结算
if (useDay > lastModel.DayCount)
{
useDay = lastModel.DayCount;
}
if (lastModel.DayCount <= 0)
{
LogHelper.Info("订单已经结束了还有时长订单:" + orderItem.ToJson());
continue;
}
//消耗价值
var usePrice = lastModel.ActPrice / lastModel.DayCount * useDay;
var orderPrice = lastModel.LastOrderPrice / lastModel.DayCount * useDay;
//var useCostPrice = lastModel.LastCostPrice / lastModel.DayCount * useDay;
//支付金额
var payPrice = lastModel.ActPrice - usePrice;
//剩余价值
var actPrice = lastModel.ActPrice - usePrice;
//订单金额
var lastOrderPrice = lastModel.LastOrderPrice - orderPrice;
//var lastCostPrice = lastModel.LastCostPrice - useCostPrice;
var orderCount = lastModel.DayCount - useDay;
//剩余天数
var dayCount = lastModel.DayCount - useDay;
var lastPrice = lastModel.ActPrice;
var lastDayCount = lastModel.DayCount;
//记收入跟预收
decimal income = usePrice;
decimal depositreceived = 0;
//记成本跟剩余成本
decimal costPrice = orderPrice ?? 0;
decimal lastCostPrice = 0;
var guid = Guid.NewGuid().ToString();
//写入状态表
actList.Add(new Model.EntityAudit.Mon_Order_Module_Act(guid, sTime, lastModel.UserName, lastModel.ModuleId, lastPrice, -usePrice, payPrice, actPrice, lastDayCount, useDay, orderCount, dayCount, lastModel.OrderId, sTime, "状态变化结算(免费单)", lastModel.OTime, lastModel.Channel, -orderPrice, lastOrderPrice, costPrice, lastCostPrice, lastModel.CostRate, income, depositreceived, int.Parse(sTime.ToString("yyyyMM"))) { FinishStatus = 0 });
//写入结算表
//_monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, sTime, 0, usePrice, 0, useDay, lastModel.OrderId, lastModel.OTime, lastModel.Channel, lastModel.UserName, useOrderPrice, 0, useCostPrice, 0));
}
/******计算消耗价值 end********/
/******重新计算价值****************/
//重新获取一次
//lastOrder = actList.Where(p => p.OrderId == orderKey.orderid && p.ActDay <= sTime && p.Status == 0).ToList();
lastOrder = actList.Where(p => p.OrderId == orderKey.orderid && p.Status == 0).ToList();
//需要计算公允价的订单
var lastOrderDict = new List<string>();
foreach (var item in lastOrder)
{
if (item.DayCount > 0)
lastOrderDict.Add(item.ModuleId + "," + item.DayCount);
}
foreach (var order in orderItem)
{
if (order.opendays > 0)
lastOrderDict.Add(order.moduleid + "," + order.opendays);
}
//剩余价值
var shengyuPayPrice = lastOrder.Sum(p => p.ActPrice);
var shengyuOrderPrice = lastOrder.Sum(p => p.OrderPrice);
//var shengyuCostPrice = lastOrder.Sum(p => p.CostPrice);
decimal totalPrice = 0 + shengyuPayPrice;
decimal tfPrice = 0;
decimal? costRate = null;
//已存在的订单数据
foreach (var lastModel in lastOrder)
{
//if (lastModel.DayCount <= 0)
//{
// continue;
//}
lastModel.Status = 1;
//支付金额
var payPrice = JiSuanPrice(lastModel.ModuleId, lastModel.DayCount, lastOrderDict, 0, shengyuPayPrice);
//剩余金额
var actPrice = JiSuanPrice(lastModel.ModuleId, lastModel.DayCount, lastOrderDict, 0, shengyuPayPrice);
//订单金额
decimal orderPrice = 0;
//成本金额
decimal? costPrice = null;
//订单剩余金额
decimal lastOrderPrice = 0;
//剩余成本金额
decimal? lastCostPrice = null;
//if (orderPayInfo.Rate.HasValue && orderPayInfo.Rate.Value > 0)
if (lastModel.CostRate.HasValue && lastModel.CostRate.Value > 0)
{
//orderPrice = modulePrice * (1 - orderPayInfo.Rate.Value);
//lastOrderPrice = actPrice * orderPayInfo.Rate.Value;
lastOrderPrice = actPrice * lastModel.CostRate.Value;
costRate = lastModel.CostRate.Value;
}
//else
//{
// orderPrice = modulePrice;
//}
//avgRefundPrice = refundPrice * (item.ActPrice / refundDeno);
//消耗价值
var usePrice = 0;
//消耗时长
var useDayCount = 0;
//var useOrderPrice = 0;
//var useCostPrice = 0;
//上个状态剩余价值
var lastPrice = 0;
//上个状态剩余时长
var lastDayCount = 0;
//var lastOrderPrice = 0;
//var lastCostPrice = 0;
var orderCount = lastModel.DayCount;
var dayCount = lastModel.DayCount;
//记收入跟预收
decimal income = 0;
decimal depositreceived = 0;
var info = new Model.EntityAudit.Mon_Order_Module_Act(Guid.NewGuid().ToString(), lastModel.ActDay, lastModel.UserName, lastModel.ModuleId, lastPrice, usePrice, payPrice, actPrice, lastDayCount, useDayCount, orderCount, dayCount, lastModel.OrderId, sTime, "新订单(免费单写入重算)", lastModel.OTime, lastModel.Channel, orderPrice, lastOrderPrice, costPrice, lastCostPrice, lastModel.CostRate, income, depositreceived, null);
actList.Add(info);
tfPrice += (actPrice + income);
}
//新的订单数据
foreach (var order in orderItem)
{
//支付金额
var payPrice = JiSuanPrice(order.moduleid, order.opendays.Value, lastOrderDict, 0, shengyuPayPrice);
//剩余金额
var actPrice = JiSuanPrice(order.moduleid, order.opendays.Value, lastOrderDict, 0, shengyuPayPrice);
//订单金额
decimal orderPrice = 0;
//成本金额
decimal? costPrice = null;
//订单剩余金额
decimal lastOrderPrice = 0;
//剩余成本金额
decimal? lastCostPrice = null;
//if (orderPayInfo.Rate.HasValue && orderPayInfo.Rate.Value > 0)
if (costRate.HasValue && costRate.Value > 0)
{
//orderPrice = modulePrice * (1 - orderPayInfo.Rate.Value);
//lastOrderPrice = actPrice * orderPayInfo.Rate.Value;
lastOrderPrice = actPrice * costRate.Value;
}
//else
//{
// orderPrice = modulePrice;
//}
//消耗价值
var usePrice = 0;
//消耗时长
var useDayCount = 0;
//var useOrderPrice = 0;
//var useCostPrice = 0;
//上个状态剩余价值
var lastPrice = 0;
//上个状态剩余时长
var lastDayCount = 0;
//var lastOrderPrice = 0;
//var lastCostPrice = 0;
var orderCount = order.opendays.Value;
var dayCount = order.opendays.Value;
//记收入跟预收
decimal income = 0;
decimal depositreceived = 0;
actList.Add(new Model.EntityAudit.Mon_Order_Module_Act(Guid.NewGuid().ToString(), order.stime, order.username, order.moduleid, lastPrice, usePrice, payPrice, actPrice, lastDayCount, useDayCount, orderCount, dayCount, order.orderid, sTime, "免费单", order.otime, order.channel, orderPrice, lastOrderPrice, costPrice, lastCostPrice, costRate, income, depositreceived, null));
tfPrice += (actPrice + income);
}
if (totalPrice.ToString("#0.00") != tfPrice.ToString("#0.00"))
{
LogHelper.Info("免费单摊分金额错误totalPrice" + totalPrice.ToString() + "tfPrice" + tfPrice.ToString() + "---" + orderItem.ToJson());
//throw new Exception("error");
}
}
}
}
//退款单
//if (orderRefundItem.Any())
//{
/******退款处理*****/
foreach (var refundItem in orderRefundItem)
{
var refundPrice = Convert.ToDecimal(refundItem.refundprice.Value);
//var ismorepay = refundItem.ismorepay;
//if (ismorepay == 1)
//{
//}
//else
//{
var refundModeleItem = actList.Where(p => p.OrderId == refundItem.orderid && p.Status == 0).ToList();
if (refundModeleItem.Any())
{
foreach (var item in refundModeleItem)
{
var lastModel = item;
lastModel.Status = 1;
//消耗天数
var actDay = DateTime.Parse(lastModel.ActDay.ToShortDateString());
var ts = sTime.Subtract(actDay);
var useDay = ts.Days;
//退款时UseDay为负数时设置为0
if (useDay < 0) useDay = 0;// 还没开始执行
if (useDay > 0)
{
//更新原来的状态为已结
lastModel.Status = 1;
}
//结算时已过期,按剩余天数结算
if (useDay > lastModel.DayCount)
{
useDay = lastModel.DayCount;
}
//消耗价值
decimal usePrice = 0;
decimal orderPrice = 0;
//decimal useCostPrice = 0;
if (lastModel.DayCount > 0)
{
usePrice = lastModel.ActPrice / lastModel.DayCount * useDay;
orderPrice = lastModel.LastOrderPrice.Value / lastModel.DayCount * useDay;
//useCostPrice = lastModel.LastCostPrice.Value / lastModel.DayCount * useDay;
}
//支付金额
var payPrice = lastModel.ActPrice - usePrice;
//剩余金额
var actPrice = lastModel.ActPrice - usePrice;
//订单金额
var lastOrderPrice = lastModel.LastOrderPrice - orderPrice;
//成本金额
//var lastCostPrice = lastModel.LastCostPrice - costPrice;
var orderCount = lastModel.DayCount - useDay;
//剩余天数
var dayCount = lastModel.DayCount - useDay;
var lastPrice = lastModel.ActPrice;
var lastDayCount = lastModel.DayCount;
//记收入跟预收
decimal income = usePrice;
decimal depositreceived = 0;
//记成本跟剩余成本
decimal costPrice = orderPrice;
decimal lastCostPrice = 0;
var guid = Guid.NewGuid().ToString();
//写入状态表
actList.Add(new Model.EntityAudit.Mon_Order_Module_Act(guid, sTime, lastModel.UserName, lastModel.ModuleId, lastPrice, -usePrice, payPrice, actPrice, lastDayCount, useDay, orderCount, dayCount, lastModel.OrderId, sTime, "状态变化结算(退款)", lastModel.OTime, lastModel.Channel, -orderPrice, lastOrderPrice, costPrice, lastCostPrice, lastModel.CostRate, income, depositreceived, int.Parse(sTime.ToString("yyyyMM"))) { FinishStatus = 0 });
//写入结算表
//_monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, sTime, 0, usePrice, 0, useDay, lastModel.OrderId, lastModel.OTime, lastModel.Channel, lastModel.UserName, useOrderPrice, 0, useCostPrice, 0));
}
//重新获取
refundModeleItem = actList.Where(p => p.OrderId == refundItem.orderid && p.Status == 0).ToList();
var refundDeno = refundModeleItem.Sum(p => p.ActPrice);
////退款金额平分
//var avgRefundPrice = refundPrice / refundModeleItem.Count();
//decimal costRefundPrice = 0;
//if (orderPayInfo.Rate.HasValue && orderPayInfo.Rate.Value > 0)
//{
// costRefundPrice = avgRefundPrice * orderPayInfo.Rate.Value;
//}
//var orderRefundPrice = avgRefundPrice - costRefundPrice;
foreach (var item in refundModeleItem)
{
var lastModel = item;
lastModel.Status = 1;
//退款金额
decimal avgRefundPrice = 0;
if (refundDeno > 0)
{
avgRefundPrice = refundPrice * (item.ActPrice / refundDeno);
}
else
{
//如果剩余金额已经消耗完了
avgRefundPrice = refundPrice / refundModeleItem.Count();
}
//avgRefundPrice = refundPrice * (item.ActPrice / refundDeno);
var income = lastModel.ActPrice;
var costPrice = lastModel.LastOrderPrice;
var guid2 = Guid.NewGuid().ToString();
var actModel2 = new Model.EntityAudit.Mon_Order_Module_Act(guid2, sTime, lastModel.UserName, lastModel.ModuleId, 0, 0, 0, 0, 0, lastModel.DayCount, lastModel.DayCount, 0, lastModel.OrderId, sTime, "退款结算", lastModel.OTime, lastModel.Channel, 0, 0, costPrice, 0, lastModel.CostRate, income, 0, int.Parse(sTime.ToString("yyyyMM")))
{
Status = 1,
FinishStatus = 0
};
actList.Add(actModel2);
//写入结算表
//_monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid2, sTime, 0, lastModel.ActPrice, 0, lastModel.DayCount, lastModel.OrderId, lastModel.OTime, lastModel.Channel, lastModel.UserName, lastModel.LastOrderPrice, 0, lastModel.LastCostPrice, 0));
decimal avgCostPrice = 0;
if (lastModel.Channel >= 25000 && lastModel.Channel <= 26199)
{
if (orderPayInfo.Rate.HasValue && avgRefundPrice * orderPayInfo.Rate.Value > 0)
{
avgCostPrice = -1 * avgRefundPrice * orderPayInfo.Rate.Value;
}
}
var guid = Guid.NewGuid().ToString();
var actModel = new Model.EntityAudit.Mon_Order_Module_Act(guid, sTime, lastModel.UserName, lastModel.ModuleId, 0, 0, 0, 0, 0, 0, 0, 0, lastModel.OrderId, sTime, "退款", lastModel.OTime, lastModel.Channel, 0, 0, avgCostPrice, 0, lastModel.CostRate, -avgRefundPrice, 0, int.Parse(sTime.ToString("yyyyMM")))
{
Status = 2,
FinishStatus = 0
};
actList.Add(actModel);
//if (lastModel.Channel >= 25000 && lastModel.Channel <= 26199)
//{
// //短线王 特殊处理
// decimal avgCostPrice = 0;
// if (orderPayInfo.Rate.HasValue && avgRefundPrice * orderPayInfo.Rate.Value > 0)
// {
// avgCostPrice = avgRefundPrice * orderPayInfo.Rate.Value;
// }
// //短线王
// _monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, sTime, 2, -avgRefundPrice, 0, 0, lastModel.OrderId, lastModel.OTime, lastModel.Channel, lastModel.UserName, 0, 0, -avgCostPrice, 0));
//}
//else
//{
// _monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, sTime, 2, -avgRefundPrice, 0, 0, lastModel.OrderId, lastModel.OTime, lastModel.Channel, lastModel.UserName, 0, 0, 0, 0));
//}
}
}
else
{
var lastModel = actList.Find(p => p.OrderId == refundItem.orderid);
if (lastModel == null)
{
lastModel = _orderModuleAct.Get(p => p.OrderId == refundItem.orderid);
}
if (lastModel == null)
{
LogHelper.Info(String.Format("{0},为空", refundItem.orderid));
}
var payRefundPrice = Convert.ToDecimal(refundItem.refundprice.Value);
decimal costRefundPrice = 0;
//var orderRefundPrice = payRefundPrice - costRefundPrice;
if (lastModel.Channel >= 25000 && lastModel.Channel <= 26199)
{
if (orderPayInfo.Rate.HasValue && orderPayInfo.Rate.Value > 0)
{
costRefundPrice = -1 * payRefundPrice * orderPayInfo.Rate.Value;
}
}
var guid = Guid.NewGuid().ToString();
var actModel = new Model.EntityAudit.Mon_Order_Module_Act(guid, sTime, lastModel.UserName, lastModel.ModuleId, 0, 0, 0, 0, 0, 0, 0, 0, lastModel.OrderId, sTime, "到期退款", lastModel.OTime, lastModel.Channel, 0, 0, costRefundPrice, 0, lastModel.CostRate, -payRefundPrice, 0, int.Parse(sTime.ToString("yyyyMM")))
{
Status = 2,
FinishStatus = 0
};
actList.Add(actModel);
//if (lastModel.Channel >= 25000 && lastModel.Channel <= 26199)
//{
// //短线王
// _monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, sTime, 2, -payRefundPrice, 0, 0, lastModel.OrderId, lastModel.OTime, lastModel.Channel, lastModel.UserName, 0, 0, -costRefundPrice, 0));
//}
//else
//{
// _monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, sTime, 2, -payRefundPrice, 0, 0, lastModel.OrderId, lastModel.OTime, lastModel.Channel, lastModel.UserName, 0, 0, 0, 0));
//}
}
//}
}
//}
//}
//catch (Exception ex)
//{
// LogHelper.Info("stime:" + sTime.ToString() + "---" + orderKey.ToJson());
// LogHelper.Error(ex);
// throw;
//}
}
}
sTime = sTime.AddDays(1);
ExecOrderModuleIncome(aTime);//自动执行月结算
}
foreach (var item in _dic2)
{
foreach (var subitem in item.Value)
{
if (subitem.UserName == "dn0269805")
{
LogHelper.Info("orderid:" + subitem.OrderId + ",ctime:" + subitem.CTime.ToString() + ",remark:" + subitem.Remark);
}
_monOrderModuleActList.Add(
new Model.EntityAudit.Mon_Order_Module_Act(subitem.Id, subitem.ActDay, subitem.UserName, subitem.ModuleId, subitem.LastPrice, subitem.UsePrice, subitem.PayPrice, subitem.ActPrice, subitem.LastDayCount, subitem.UseDayCount, subitem.OrderCount, subitem.DayCount, subitem.OrderId, subitem.CTime, subitem.Remark, subitem.OTime, subitem.Channel, subitem.OrderPrice, subitem.LastOrderPrice, subitem.CostPrice, subitem.LastCostPrice, subitem.CostRate, subitem.InCome, subitem.DepositReceived, subitem.FinishMonth)
{
Status = subitem.Status,
FinishStatus = subitem.FinishStatus
}
);
}
}
////if (_monOrderModuleActList.Any() && _monOrderModuleIncome.Any())
//if (_monOrderModuleActList.Any())
//{
// //之前未处理的数据,已经加载处理,所以之前的数据做删除操作
// //var ret = _orderModuleAct.Delete(p => p.Status == 0);
// //if (ret)
// //{
// // ////_monOrderModuleActList.RemoveAll(p => p.OMonth < omonth);
// // _orderModuleAct.BulkInsertToMysql("Mon_Order_Module_Act", _monOrderModuleActList);
// // ////_orderModelIncome.BulkInsertToMysql("Mon_Order_Module_Income", _monOrderModuleIncome);
// //}
// _orderModuleAct.InitData();
// _orderModuleAct.BulkInsertToMysql("mon_order_module_act_yg", _monOrderModuleActList);
//}
}
public void ExecOrderModuleIncome(DateTime sTime)
{
//本月第一天
var monthFirsthDay = sTime.AddDays(1 - sTime.Day);
//本月最后一天
//var monthLastDay = sTime.AddDays(1 - sTime.Day).Date.AddMonths(1).AddDays(-1);
//上个月最后一天
var premonthLastDay = sTime.AddDays(-1);
//判断传入的是不是每月的第一天
var diffDays = sTime.Subtract(monthFirsthDay);
if (diffDays.Days == 0)
{
//找出所有需要结算的数据
foreach (var userModel in _dic2)
{
if (monthFirsthDay.ToString("yyyy-MM-dd") == "2019-09-01")
{
}
try
{
//先执行预收
var orderDepositList = userModel.Value.Where(p => p.Status == 0 && p.ActDay >= monthFirsthDay).ToList();
foreach (var order in orderDepositList)
{
//写入状态表
var lastprice = order.ActPrice;
var depositreceived = order.ActPrice;
var lastcostprice = order.LastOrderPrice;
var guid = Guid.NewGuid().ToString();
var monthAct = new Model.EntityAudit.Mon_Order_Module_Act(guid, order.ActDay, order.UserName, order.ModuleId, lastprice, order.UsePrice, order.PayPrice, order.ActPrice, order.LastDayCount, order.UseDayCount, order.OrderCount, order.DayCount, order.OrderId, monthFirsthDay, "预收", order.OTime, order.Channel, order.OrderPrice, order.LastOrderPrice, order.CostPrice, lastcostprice, order.CostRate, order.InCome, depositreceived, int.Parse(premonthLastDay.ToString("yyyyMM")))
{
Status = 2,
FinishStatus = 0
};
userModel.Value.Add(monthAct);
//写入结算表
//_monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, premonthLastDay, 1, 0, order.ActPrice, 0, order.OrderId, order.OTime, order.Channel, order.UserName, order.OrderPrice, order.LastOrderPrice, order.CostPrice, order.LastCostPrice));
}
//未结算并且是上个月的数据才结算
var orderActList = userModel.Value.Where(p => p.Status == 0 && p.ActDay < monthFirsthDay).ToList();
foreach (var order in orderActList)
{
//LogHelper.Info("结算order:" + order.ToJson());
if (order.ActPrice <= 0 || order.DayCount <= 0)
{
//已经没有剩余价值直接更新成已结算
//var lastAct = _monOrderActList.Find(p => p.Id == order.Id);
var lastAct = userModel.Value.Find(p => p.Id == order.Id);
lastAct.Status = 3;
/*
lastAct.FinishStatus = -1;
var guid = Guid.NewGuid().ToString();
//写入状态表
var monthAct = new Model.EntityAudit.Mon_Order_Module_Act(guid, sTime, order.UserName, order.ModuleId, order.LastPrice, -order.UsePrice, order.PayPrice, order.ActPrice, order.LastDayCount, order.UseDayCount, order.OrderCount, order.DayCount, order.OrderId, monthFirsthDay, "月结", order.OTime, order.Channel, -order.OrderPrice, order.LastOrderPrice, order.CostPrice, order.LastCostPrice, order.CostRate, 0, order.DepositReceived, int.Parse(premonthLastDay.ToString("yyyyMM")))
{
Status = 3,
FinishStatus = 0
};
userModel.Value.Add(monthAct);
*/
//写入结算表
//_monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, premonthLastDay, 1, order.ActPrice, 0, 0, order.OrderId, order.OTime, order.Channel, order.UserName, order.OrderPrice, order.LastOrderPrice, order.CostPrice, order.LastCostPrice));
continue;
}
//消耗天数
var actDay = DateTime.Parse(order.ActDay.ToShortDateString());
var ts = monthFirsthDay.Subtract(actDay);
var useDay = ts.Days;
if (useDay > order.DayCount)
{
useDay = order.DayCount;
}
//消耗价值
var usePrice = order.ActPrice / order.DayCount * useDay;
var orderPrice = order.LastOrderPrice / order.DayCount * useDay;
//var useCostPrice = order.LastCostPrice / order.DayCount * useDay;
//支付金额
var payPrice = order.ActPrice - usePrice;
//剩余价值
var actPrice = order.ActPrice - usePrice;
//剩余价值
var lastOrderPrice = order.LastOrderPrice - orderPrice;
//var lastCostPrice = order.LastCostPrice - useCostPrice;
var orderCount = order.DayCount - useDay;
//剩余天数
var dayCount = order.DayCount - useDay;
var lastPrice = order.ActPrice;
var lastDayCount = order.DayCount;
//记收入跟预收
decimal income = usePrice;
decimal depositreceived = actPrice;
//记成本跟剩余成本
decimal costPrice = orderPrice ?? 0;
decimal lastCostPrice = lastOrderPrice ?? 0;
if (useDay <= 0)
{
//价值已经用完的情况
dayCount = 0;
actPrice = 0;
lastOrderPrice = 0;
//lastCostPrice = 0;
//更新原来的状态为已结
var lastAct = userModel.Value.Find(p => p.Id == order.Id);
lastAct.Status = 3;
//lastAct.FinishStatus = 0;
//lastAct.Remark = "月结";
var guid = Guid.NewGuid().ToString();
//写入状态表
var monthAct = new Model.EntityAudit.Mon_Order_Module_Act(guid, sTime, order.UserName, order.ModuleId, lastPrice, -usePrice, payPrice, actPrice, lastDayCount, useDay, orderCount, dayCount, order.OrderId, monthFirsthDay, "月结", order.OTime, order.Channel, -orderPrice, lastOrderPrice, costPrice, lastCostPrice, order.CostRate, income, depositreceived, int.Parse(premonthLastDay.ToString("yyyyMM")))
{
FinishStatus = 0
};
userModel.Value.Add(monthAct);
//写入结算表
//_monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, premonthLastDay, 1, order.ActPrice, lastActPrice, useDay, order.OrderId, order.OTime, order.Channel, order.UserName, order.OrderPrice, order.LastOrderPrice, order.CostPrice, order.LastCostPrice));
}
else
{
//更新原来的状态为已结
var lastAct = userModel.Value.Find(p => p.Id == order.Id);
lastAct.Status = 3;
//lastAct.FinishStatus = 0;
//lastAct.Remark = "月结";
//写入状态表
var guid = Guid.NewGuid().ToString();
var monthAct = new Model.EntityAudit.Mon_Order_Module_Act(guid, sTime, order.UserName, order.ModuleId, lastPrice, -usePrice, payPrice, actPrice, lastDayCount, useDay, orderCount, dayCount, order.OrderId, monthFirsthDay, "月结", order.OTime, order.Channel, -orderPrice, lastOrderPrice, costPrice, lastCostPrice, order.CostRate, income, depositreceived, int.Parse(premonthLastDay.ToString("yyyyMM")))
{
FinishStatus = 0
};
if (actPrice == 0 || dayCount == 0)
{
monthAct.Status = 3;
//monthAct.FinishStatus = 2;
}
userModel.Value.Add(monthAct);
//写入结算表
//_monOrderModuleIncome.Add(new Model.EntityAudit.Mon_Order_Module_Income(guid, premonthLastDay, 1, usePrice, lastActPrice, useDay, order.OrderId, order.OTime, order.Channel, order.UserName, useOrderPrice, lastOrderPrice, useCostPrice, lastCostPrice));
}
}
}
catch (Exception ex)
{
LogHelper.Info(userModel.ToJson());
LogHelper.Error(ex);
throw;
}
//var orderActList = _monOrderActList.Where(p => p.Status == 0).ToList();
}
}
}
#endregion
private decimal JiSuanPrice(OrderModuleDto order, IEnumerable<OrderModuleDto> orderItem, decimal orderPrice, decimal shengyuPrice)
{
decimal modulePrice = 0;
//分母
decimal deno = 0;
//分子
decimal num = 0;
foreach (var item in orderItem)
{
decimal gyj = 0;
if (gyjList.TryGetValue(item.moduleid, out gyj))
{
//找到模块公允价
//var gyj = gyjList.First(p => p.Key == item.moduleid).Value;
if (gyj == 0)
{
gyj = orderPrice + shengyuPrice;
}
//公允价*时长
deno += gyj * item.opendays.Value;
}
else
{
//deno = 1;
deno += 1 * item.opendays.Value == 0 ? 1 : item.opendays.Value;
}
}
if (gyjList.ContainsKey(order.moduleid))
{
//找到模块公允价
decimal gyj = 0;
//var gyj = gyjList.First(p => p.Key == order.moduleid).Value;
if (gyjList.TryGetValue(order.moduleid, out gyj))
{
if (gyj == 0)
{
gyj = orderPrice + shengyuPrice;
}
}
//公允价*时长
num = (orderPrice + shengyuPrice) * gyj * order.opendays.Value;
modulePrice = Convert.ToDecimal(num) / Convert.ToDecimal(Convert.ToDecimal(deno == 0 ? 1 : deno));
}
else
{
if (order.opendays.Value == 0)
order.opendays = 1;
modulePrice = Convert.ToDecimal(orderPrice + shengyuPrice) * (order.opendays.Value / deno);
}
return modulePrice;
}
//订单比例价值
private decimal JiSuanRatePirce(OrderModuleDto order, IEnumerable<OrderModuleDto> orderItem, decimal orderPrice, decimal shengyuPrice, decimal payPrice)
{
decimal modulePrice = 0;
//分母
decimal deno = 0;
//分子
decimal num = 0;
foreach (var item in orderItem)
{
if (gyjList.ContainsKey(item.moduleid))
{
//找到模块公允价
//var gyj = gyjList.First(p => p.Key == item.moduleid).Value;
decimal gyj = 0;
if (gyjList.TryGetValue(item.moduleid, out gyj))
{
if (gyj == 0)
{
gyj = orderPrice + shengyuPrice;
}
}
//公允价*时长
deno += gyj * item.opendays.Value;
}
else
{
//deno = 1;
deno += 1 * item.opendays.Value == 0 ? 1 : item.opendays.Value;
}
}
if (gyjList.ContainsKey(order.moduleid))
{
//找到模块公允价
//var gyj = gyjList.First(p => p.Key == order.moduleid).Value;
decimal gyj = 0;
if (gyjList.TryGetValue(order.moduleid, out gyj))
{
if (gyj == 0)
{
//1028模块公允价处理
gyj = orderPrice + shengyuPrice;
}
}
//公允价*时长
num = payPrice * gyj * order.opendays.Value;
modulePrice = Convert.ToDecimal(num) / Convert.ToDecimal(Convert.ToDecimal(deno == 0 ? 1 : deno));
}
else
{
if (order.opendays.Value == 0)
order.opendays = 1;
modulePrice = payPrice * (order.opendays.Value / deno);
}
return modulePrice;
}
private decimal JiSuanPrice(string moduleid, int opendays, List<string> orderItem, decimal orderPrice, decimal shengyuPrice)
{
decimal modulePrice = 0;
//分母
decimal deno = 0;
//分子
decimal num = 0;
foreach (var item in orderItem)
{
var arr = item.Split(',');
var key = arr[0].ToString();
var value = decimal.Parse(arr[1]);
if (gyjList.ContainsKey(key))
{
//找到模块公允价
//var gyj = gyjList.First(p => p.Key == key).Value;
decimal gyj = 0;
if (gyjList.TryGetValue(key, out gyj))
{
if (gyj == 0)
{
//1028模块公允价处理
gyj = orderPrice + shengyuPrice;
}
}
//公允价*时长
deno += gyj * value;
}
else
{
//deno = 1;
deno += 1 * value == 0 ? 1 : value;
}
}
if (gyjList.ContainsKey(moduleid))
{
//找到模块公允价
//var gyj = gyjList.First(p => p.Key == moduleid).Value;
decimal gyj = 0;
if (gyjList.TryGetValue(moduleid, out gyj))
{
if (gyj == 0)
{
//1028模块公允价处理
gyj = orderPrice + shengyuPrice;
}
}
//公允价*时长
num = (orderPrice + shengyuPrice) * gyj * opendays;
modulePrice = Convert.ToDecimal(num) / Convert.ToDecimal(deno == 0 ? 1 : deno);
}
else
{
//modulePrice = Convert.ToDecimal(orderPrice + shengyuPrice);
if (opendays == 0)
opendays = 1;
modulePrice = Convert.ToDecimal((orderPrice + shengyuPrice) * (opendays / deno));
}
return modulePrice;
}
public List<IncomeDto> GetIncomeJieSuan()
{
var dto = new List<IncomeDto>();
var endTime = DateTime.Parse("2022-01-01");
var incomeData = _orderModelIncome.GetIncome();
var modulepriceData = _modulePrice.GetModulePrice(endTime);
var moduleRefundData = _moduleRefund.GetRefund(endTime);
var refundTotalData = _refund.GetRefundTotal(endTime);
var refundNotUseData = _refund.GetNotUsedRefund(endTime);
var payPriceData = _orderPay.GetPayList(endTime);
var payPriceUseData = _payClear.GetPayClearList(endTime);
foreach (var item in incomeData)
{
double moduelPrice = 0;
var moduelInfo = modulepriceData.Find(p => p.oMonth == item.actMonth);
if (moduelInfo != null)
{
moduelPrice = moduelInfo.modulePrice;
}
decimal refundUse = 0;
var refundUseInfo = moduleRefundData.Find(p => p.fMonth == item.actMonth);
if (refundUseInfo != null)
{
refundUse = refundUseInfo.refundPrice;
}
decimal refundSum = 0;
var refundTotalInfo = refundTotalData.Find(p => p.fMonth == item.actMonth);
if (refundTotalInfo != null)
{
refundSum = refundTotalInfo.refundPrice;
}
decimal refundNotUse = 0;
var refundNotUseInfo = refundNotUseData.Find(p => p.fMonth == item.actMonth);
if (refundNotUseInfo != null)
{
refundNotUse = refundNotUseInfo.refundPrice;
}
decimal payPrice = 0;
decimal payPriceSum = 0;
var payPriceInfo = payPriceData.Find(p => p.pMonth == item.actMonth);
if (payPriceInfo != null)
{
payPrice = payPriceInfo.payPrice;
payPriceSum = payPriceInfo.payPriceSum;
}
decimal payPriceUse = 0;
decimal payPriceUseSum = 0;
var payPriceUseInfo = payPriceUseData.Find(p => p.uMonth == item.actMonth);
if (payPriceUseInfo != null)
{
payPriceUse = payPriceUseInfo.usePrice;
payPriceUseSum = payPriceUseInfo.usePriceSum;
}
var info = new IncomeDto(
item.actMonth,
item.income,
item.incomeSum,
item.depositreceived,
item.orderPriceSum,
item.netAmount,
moduelPrice,
refundUse,
refundSum,
refundNotUse,
payPrice,
payPriceSum,
payPriceUse,
payPriceUseSum,
payPriceNotUse: payPriceSum - payPriceUseSum
);
dto.Add(info);
}
return dto;
}
public retMsg<ExportItemMsg> ExportAuditExcel(string queryType)
{
retMsg<ExportItemMsg> retMsg = new retMsg<ExportItemMsg>()
{
result = true
};
Stopwatch stopwatch = Stopwatch.StartNew();
QueryAudit queryAudit = new QueryAudit();
var exportItems = queryAudit.QueryAuditItems(queryType);
stopwatch.Stop();
var querytims = stopwatch.ElapsedMilliseconds;
stopwatch.Restart();
ExportAudit exportAudit = new ExportAudit();
retMsg = exportAudit.ExportAudit_xlsx(exportItems, queryType);
stopwatch.Stop();
Logger.Info($"ExportAuditExcel,查询耗时:{querytims},导出耗时{stopwatch.ElapsedMilliseconds}");
return retMsg;
}
public retMsg SetChannelByEid(int orderid, int channel, string deptcode)
{
using (var db = new zxdContext())
{
using (var trans = db.Database.BeginTransaction())
{
try
{
var order = db.WX_SZZYORDER.FirstOrDefault(p => p.ORDERID == orderid);
if (order != null)
{
order.CHANNEL = channel;
order.deptcode = deptcode;
var payList = db.WX_SzzyOrderPay.Where(p => p.orderid == orderid);
foreach (var pay in payList)
{
pay.channel = channel;
pay.deptcode = deptcode;
}
var deposits = payList.Where(p => p.depositid.HasValue).Select(p => p.depositid).ToList();
foreach (var item in deposits)
{
//找到到账信息
var deps = db.WX_SzzyOrderDeposit.Where(p => p.id == item);
foreach (var dep in deps)
{
dep.channel = channel;
dep.deptcode = deptcode;
}
}
var refundList = db.WX_SzzyOrderRefund.Where(p => p.orderid == orderid);
foreach (var refund in refundList)
{
refund.channel = channel;
refund.deptcode = deptcode;
}
//旧的订金数据
var depList = db.WX_SzzyOrderDeposit.Where(p => p.orderid == orderid);
foreach (var dep in depList)
{
dep.channel = channel;
dep.deptcode = deptcode;
}
db.SaveChanges();
}
trans.Commit();
return new retMsg { result = true, retcode = 200 };
}
catch (Exception ex)
{
LogHelper.Error(ex);
trans.Rollback();
return new retMsg { result = false, retcode = 500 };
}
}
}
}
public retMsg OrderSync(int orderId)
{
var order = _order.Get(p => p.ORDERID == orderId);
if (order == null)
{
return new retMsg { result = false, retcode = 100, retmsg = "未能找到订单" };
}
//推送到分部
Common.EventBus.EventBus.Instance.Publish(new SupplyOrderEvent(order));
return new retMsg { result = true, retcode = 200, retmsg = "success" };
}
/// <summary>
/// 平台一到账确认回调
/// </summary>
/// <param name="szzyOrderId">订单权限单号</param>
/// <param name="payTime">支付时间</param>
/// <param name="payAmount">支付金额(分)</param>
public retMsg CallBackPayPT1(decimal? szzyOrderId, DateTime? payDate, decimal? payPrice)
{
try
{
if (!szzyOrderId.HasValue)
{
Logger.Info("平台一支付到账回调szzyOrderId为空!");
return new retMsg { result = false, retcode = 100, retmsg = "para error" };
}
if (!payDate.HasValue)
{
Logger.Info("平台一支付到账回调payTime为空!");
return new retMsg { result = false, retcode = 100, retmsg = "para error" };
}
if (!payPrice.HasValue)
{
Logger.Info("平台一支付到账回调payAmount为空!");
return new retMsg { result = false, retcode = 100, retmsg = "para error" };
}
var url = paramter_bl.GetValue_Parameter("CallBackPayUrlPT1");
var key = "1633a92d";
var callbackpaykeypt1 = paramter_bl.GetValue_Parameter("CallBackPayKeyPT1");
if (!string.IsNullOrEmpty(callbackpaykeypt1))
{
key = callbackpaykeypt1;
}
var timestamp = DateTimeTool.ConvertDateTimeLong(DateTime.Now);
var orderid = szzyOrderId.ToString();
var payTime = payDate.Value.ToString("yyyy-MM-dd");
var payAmount = Convert.ToInt32(payPrice * 100);
var source = orderid + payAmount.ToString() + payTime + timestamp.ToString() + key;
Logger.Info("平台一支付到账回调source" + source);
var util = new EncDecUtil();
var sign = util.signData(source, key);
Logger.Info("平台一支付到账回调sign" + sign);
var para = new { orderId = orderid, payTime = payTime, payAmount = payAmount, timestamp = timestamp, sign = sign };
Logger.Info("平台一支付到账回调参数:" + para);
var rsp = Utility.PostAjaxData(url, para.ToJson(), Encoding.UTF8);
Logger.Info("平台一支付到账回调结果:" + rsp);
var ret = JsonConvert.DeserializeAnonymousType(rsp, new { code = 0, msg = string.Empty });
if (ret.code == 1000)
{
return new retMsg { result = true, retcode = 200, retmsg = "success" };
}
else
{
return new retMsg { result = false, retcode = ret.code, retmsg = ret.msg };
}
}
catch (Exception ex)
{
Logger.Error(ex);
return new retMsg { result = false, retcode = 500, retmsg = "sys error" };
}
}
public retMsg CallBackRefundPT1(string outorderNo, DateTime? refundTime, decimal? refundPrice)
{
try
{
if (string.IsNullOrEmpty(outorderNo))
{
Logger.Info("平台一退款回调outorderNo为空!");
return new retMsg { result = false, retcode = 100, retmsg = "para error" };
}
if (!refundTime.HasValue)
{
Logger.Info("平台一退款回调refundTime为空!");
return new retMsg { result = false, retcode = 100, retmsg = "para error" };
}
if (!refundPrice.HasValue)
{
Logger.Info("平台一退款回调refundPrice为空!");
return new retMsg { result = false, retcode = 100, retmsg = "para error" };
}
var url = paramter_bl.GetValue_Parameter("CallBackRefundUrlPT1");
var key = "1633a92d";
var callbackpaykeypt1 = paramter_bl.GetValue_Parameter("CallBackPayKeyPT1");
if (!string.IsNullOrEmpty(callbackpaykeypt1))
{
key = callbackpaykeypt1;
}
var refund_time = DateTimeTool.ConvertDateTimeLong(refundTime.Value);
var order_no = outorderNo;
var amount = refundPrice.Value;
var source = order_no + refund_time.ToString() + amount.ToString() + key;
Logger.Info("平台一退款回调source" + source);
var util = new EncDecUtil();
var sign = util.signData(source, key);
Logger.Info("平台一退款回调sign" + sign);
var para = new { order_no = order_no, refund_time = refund_time, amount = amount, sign = sign };
Logger.Info("平台一退款回调参数:" + para);
var rsp = Utility.PostAjaxData(url, para.ToJson(), Encoding.UTF8);
Logger.Info("平台一退款回调结果:" + rsp);
var ret = JsonConvert.DeserializeAnonymousType(rsp, new { code = 0, msg = string.Empty });
if (ret.code == 1000)
{
return new retMsg { result = true, retcode = 200, retmsg = "success" };
}
else
{
return new retMsg { result = false, retcode = ret.code, retmsg = ret.msg };
}
}
catch (Exception ex)
{
Logger.Error(ex);
return new retMsg { result = false, retcode = 500, retmsg = "sys error" };
}
}
private void OpenOrderEventExec(decimal orderId, string orderStatus, string orderStatusName, DateTime oTime, DateTime endTime, string companyCode, string activeProductCode, string activeProductExt, string cName, string resId, int? operaId, string operaName)
{
//Common.EventBus.EventBus.Instance.Publish(new OpenOrderEvent(Convert.ToInt32(orderId), orderStatus, orderStatusName, oTime, endTime, companyCode, activeProductCode, activeProductExt, cName, resId, operaId, operaName));
OrderSync(Convert.ToInt32(orderId));
}
private void OpenOrderSendSmsExec(int orderId, string softUserName, string productName, string openDays, string donateDays, string resId)
{
Common.EventBus.EventBus.Instance.Publish(new OpenOrderSendSmsEvent(orderId, softUserName, productName, openDays, donateDays, resId));
}
public class IncomeDto
{
public IncomeDto()
{
}
public IncomeDto(int yearMonth, decimal income, decimal incomeSum, decimal depositreceived, decimal orderPriceSum, decimal netAmount, double modulePrice, decimal refundUse, decimal refundSum, decimal refundNotUse, decimal payPrice, decimal payPriceSum, decimal payPriceUse, decimal payPriceUseSum, decimal payPriceNotUse)
{
YearMonth = yearMonth;
Income = income;
IncomeSum = incomeSum;
Depositreceived = depositreceived;
OrderPriceSum = orderPriceSum;
NetAmount = netAmount;
ModulePrice = modulePrice;
RefundUse = refundUse;
RefundSum = refundSum;
RefundNotUse = refundNotUse;
PayPrice = payPrice;
PayPriceSum = payPriceSum;
PayPriceUse = payPriceUse;
PayPriceUseSum = payPriceUseSum;
PayPriceNotUse = payPriceNotUse;
}
/// <summary>
/// 月份
/// </summary>
public int YearMonth { get; set; }
/// <summary>
/// 收入
/// </summary>
public decimal Income { get; set; }
/// <summary>
/// 收入累计
/// </summary>
public decimal IncomeSum { get; set; }
/// <summary>
/// 预收
/// </summary>
public decimal Depositreceived { get; set; }
/// <summary>
/// 订单金额累计
/// </summary>
public decimal OrderPriceSum { get; set; }
/// <summary>
/// 净额
/// </summary>
public decimal NetAmount { get; set; }
/// <summary>
/// 订单金额
/// </summary>
public double ModulePrice { get; set; }
/// <summary>
/// 已使用退款
/// </summary>
public decimal RefundUse { get; set; }
/// <summary>
/// 总退款
/// </summary>
public decimal RefundSum { get; set; }
/// <summary>
/// 未使用退款
/// </summary>
public decimal RefundNotUse { get; set; }
/// <summary>
/// 实际收款
/// </summary>
public decimal PayPrice { get; set; }
/// <summary>
/// 收款累计
/// </summary>
public decimal PayPriceSum { get; set; }
/// <summary>
/// 收款使用
/// </summary>
public decimal PayPriceUse { get; set; }
/// <summary>
/// 收款使用累计
/// </summary>
public decimal PayPriceUseSum { get; set; }
/// <summary>
/// 收款未使用
/// </summary>
public decimal PayPriceNotUse { get; set; }
}
}
}