old_flsystem/应用/JDRebate/Class1.cs

939 lines
56 KiB
C#
Raw Normal View History

2022-09-20 03:10:29 +00:00
using Api.Framework;
using Api.Framework.Cps;
using Api.Framework.Enums;
using Api.Framework.Events;
using Api.Framework.Model;
using Api.Framework.SDK;
using Api.Framework.Timers;
using Api.Framework.Tools;
using Api.Framework.Utils;
using Chat.Framework.WXSdk;
using CsharpHttpHelper;
using JDRebate.Entitys;
using JDRebate.Properties;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using static JDRebate.Enums;
namespace JDRebate
{
public class Class1 : Plugin
{
public Class1()
{
this.Name = Resources.PluginName;
this.Note = Resources.PluginNote;
this.Logo = Resources.;
}
#region
public static Config Config;
private MainForm mainForm = null;
// public static VariateReplace variateReplace = null;
#endregion
public override void Start()
{
try
{
var session = ApiClient.GetSession();
#region
#endregion
//创建配置文件
Config = this.ReadConfig<Config>();
// variateReplace = new VariateReplace();
SDK.ReciveIMEvent += SDK_ReciveIMEvent;
SDK.OrderNoticeEvent += SDK_OrderNoticeEvent;
}
catch (Exception ex)
{
this.OnLog(ex.Message);
}
}
public override void ShowForm()
{
try
{
if (mainForm == null || mainForm.IsDisposed)
{
mainForm = new MainForm();
mainForm.Show();
}
mainForm.TopMost = true;
mainForm.TopMost = false;
}
catch (Exception ex)
{
this.OnLog(ex.Message);
}
}
public override void Stop()
{
try
{
SessionExt.Clear();
if (mainForm != null)
{
mainForm.CloseForm();
mainForm = null;
}
}
catch (Exception ex)
{
this.OnLog(ex.Message);
}
}
private void SDK_OrderNoticeEvent(object sender, OrderNoticeEvent e)
{
try
{
if (e.ChatType == CpsType.)
{
var session = ApiClient.GetSession();
//订单信息
var order_jd = e.Order as fl_order_jingdong;
if (order_jd == null) return;
if (e.Member != null)
{
var robot_info = session.FindRobotInfo(e.Member.robot_name, e.Member.robot_type);
if (robot_info != null)
{
var mess = string.Empty;
var point = HttpHelper.JsonToObject<ItemPoint>(order_jd.db_point) as ItemPoint;
switch (e.OrderNoticeType)
{
case OrderNoticeType.:
if (Config.UserOrderChangeSwitch == SwitchType. && !ApiClient.Setting.SystemConfig.message_warning_switch)
{
mess = _GetOrderStateMess(order_jd.db_status, SettleType., order_jd, e.Member, point);
if (!string.IsNullOrEmpty(e.Member.username) && !string.IsNullOrEmpty(mess))
ApiClient.SendMessage(robot_info, e.Member.username, mess, order_jd.msg_groupid);
}
return;
case OrderNoticeType.:
if (Config.AgentReceivedCommissionSwitch == SwitchType.)
{
if (e.Customer != null && point.AwardOne != 0)
{
if (order_jd.db_status == SystemOrderStatus.)
mess = Config.ClientOrderRefund_OneLevelTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderPaymentInform_OneLevelTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderCountermandInform_OneLevelTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderSettlement_OneLevelTip;
}
}
break;
case OrderNoticeType.:
if (Config.AgentReceivedCommissionSwitch == SwitchType.)
{
if (e.Customer != null)
{
if (order_jd.db_status == SystemOrderStatus.)
mess = Config.ClientOrderRefund_TwoLevelTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderPaymentInform_TwoLevelTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderCountermandInform_TwoLevelTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderSettlement_TwoLevelTip;
}
}
break;
case OrderNoticeType.:
if (Config.AgentReceivedCommissionSwitch == SwitchType.)
{
if (e.Customer != null)
{
if (order_jd.db_status == SystemOrderStatus.)
mess = Config.ClientOrderRefund_ThreeLevelTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderPaymentInform_ThreeLevelTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderCountermandInform_ThreeLevelTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderSettlement_ThreeLevelTip;
}
}
break;
case OrderNoticeType.:
if (Config.PrincipalReceivedCommissionSwitch == SwitchType.)
{
if (e.Customer != null)
{
if (order_jd.db_status == SystemOrderStatus.)
mess = Config.ClientOrderRefund_LeaderTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderPaymentInform_LeaderTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderCountermandInform_LeaderTip;
else if (order_jd.db_status == SystemOrderStatus.)
mess = Config.OrderSettlement_LeaderTip;
}
}
break;
default:
break;
}
if (!ApiClient.Setting.SystemConfig.message_warning_switch && !string.IsNullOrEmpty(e.Member.username) && !string.IsNullOrWhiteSpace(mess))
ApiClient.SendMessage(robot_info, e.Member.username, new VariateReplace().CommonReplace(mess, order_jd, e.Member, point).Replace("[下级昵称]", e.Customer.realnick));
}
}
else//多人查询通知消息
{
var querys = session.Find<queryhist_temp>("select robot_name,type,userid from fl_query_hist where itemid=@itemid and adzoneid = @adzoneid and userid > 0 and crt_time>@time and is_multiple=@is_multiple group by userid,type,robot_name", new { itemid = order_jd.skuId, adzoneid = order_jd.positionId, time = DateTime.Now.AddHours(-24).ToString("yyyy-MM-dd HH:mm:ss"), is_multiple = false });
if (querys.Count > 0)
{
for (int i = 0; i < querys.Count; i++)
{
try
{
if (querys[i].type != CpsType.) continue;
//未绑定的数量
var unbound_count = int.Parse(session.FindTable($"select count(id) as num from fl_order_jingdong where orderId = @orderId and db_userid != 0", new { orderId = order_jd.orderId }).Rows[0]["num"].ToString());
if (unbound_count != 0) break;//已经被绑定直接停止
var queryhist_temp = querys[i];
var userid = queryhist_temp.userid;
var robot_name = queryhist_temp.robot_name;
var robot_info = session.Find<fl_robot_info>("select * from fl_robot_info where name = @name", new { name = robot_name }).FirstOrDefault();//机器人类型应该是没有的,直接通过机器人name查询机器人信息
if (robot_info != null)
{
Thread.Sleep(5000);
var wxbase = Chat.Framework.ChatClient.WXClient.Values.ToList().FirstOrDefault(f => f.WeixinHao == robot_name);
if (wxbase != null /*&& wxbase.WeixinType == WeixinType.Grpc微信*/ && wxbase.Status == WxStatus.线)
{
var member = session.FindMemberInfoById(userid);
if (member != null)
{
ApiClient.SendMessage(robot_info, member.username, Config.LotUserQueryBindTip.Replace("[商品标题]", order_jd.skuName));
session.ExcuteSQL("update fl_query_hist set is_multiple = @is_multiple where itemid = @itemid and adzoneid = @adzoneid and robot_name = @robotname and userid = @userid", new { is_multiple = true, itemid = order_jd.skuId, adzoneid = order_jd.positionId, robotname = robot_name, userid = member.id });
}
}
}
}
catch (Exception)
{ }
}
}
}
}
}
catch (Exception ex)
{
this.OnLog($"{ex.Message},{ex.StackTrace}");
}
}
private void SDK_ReciveIMEvent(object sender, ReciveIMEvent e)
{
Compute compute = null;
string goodName = string.Empty;
try
{
//过滤表情xml和卡片xml
if ((e.Message.Contains(@"<msg><emoji") || e.Message.StartsWith("[声音=")) && !e.Message.Contains(@"点击链接,再选择浏览器咑閞")) return;
if (!OrderHelper.IsCurrentCpsMess(e.Message, CpsType.)) return;
var db = ApiClient.GetSession();
var member = e.GetMemberinfo();
#region
if (Regex.IsMatch(e.Message.Trim(), @"^\d{11,12}$"))
{
// int i = 0;
//Next:
var orderId = e.Message.Trim(); //订单号
var orders = db.Find<fl_order_jingdong>("select * from fl_order_jingdong where orderId = @orderId", new { orderId = orderId });
var _order = orders.FirstOrDefault(f => f.db_userid != 0 && f.db_userid != member.id);
if (_order != null)
{
e.SendMessage(Config.OccupyOrderErrorTip.Replace("[订单号]", orderId));
return;
}
if (orders != null && orders.Count != 0)
{
var notices = new List<OrderNoticeEvent>();
var downJingdongTimer = new DownJingdongTimer();
#region ,
var bindOrders = orders.Where(f => f.db_userid != 0).ToList();
if (bindOrders != null && bindOrders.Count != 0)
{
foreach (var order in bindOrders)
{
var point = HttpHelper.JsonToObject<ItemPoint>(order.db_point) as ItemPoint;
member = e.GetMemberinfo(true);
if (order.db_status == SystemOrderStatus.)
e.SendMessage(new VariateReplace().CommonReplace(Config.OrderRepetBindTip, order, point, member));
else
e.SendMessage(_GetOrderStateMess(order.db_status, (order.db_status == SystemOrderStatus. ? SettleType. : SettleType.), order, member, point));
Thread.Sleep(500);
}
}
#endregion
#region ( => )
var notBindOrders = orders.Where(f => f.db_userid == 0).ToList();
if (notBindOrders != null && notBindOrders.Count != 0)
{
if (notBindOrders[0].orderTime < ApiClient.Setting.SystemConfig.allow_bind_create_order_time)
{
e.SendMessage($"订单:{orderId},已经过了有效绑定时间!");
return;
}
foreach (var order in notBindOrders)
{
if (order.db_status == SystemOrderStatus.)
order.db_endtime = DateTime.Now.AddMinutes(-5);//重新结算的话,需要将订单的冻结时间重新赋值,让后台处理
//没有绑定用户的订单进行绑定
order.db_userid = member.id;
order.db_robotname = e.RobotName;
order.db_robottype = e.RobotInfo.type;
order.msg_groupid = e.Groupid;
#region ,
//查询历史查询比例
compute = db.FindQueryRatioHist(CpsType., order.id);
if (compute == null)
{
var query_item = db.FindSingle<fl_query_hist>("select * from fl_query_hist where userid = @userid and itemid = @itemid and adzoneid = @adzoneid order by id desc", new { userid = member.id, itemid = order.skuId, adzoneid = order.positionId });
//计算公式不为空
if (query_item != null && !string.IsNullOrWhiteSpace(query_item.compute_configdic))
{
try
{
compute = JsonConvert.DeserializeObject<Compute>(query_item.compute_configdic);
var queryRatioHist = new fl_query_ratio_hist()
{
compute_config = query_item.compute_configdic,
db_orderid = order.id,
createtime = DateTime.Now,
cpstype = CpsType.
};
LogHelper.GetSingleObj().Error("历史查询记录5", JsonConvert.SerializeObject(queryRatioHist));
db.SaveOrUpdate(queryRatioHist);
}
catch (Exception ex)
{
EventClient.OnEvent("京东计算", $"获取历史查询比异常:{ex.Message}");
}
}
}
ItemPoint itempoint = null;
//计算的佣金
if (compute != null)
itempoint = db.FindItemPoint(CpsType., compute, order.actualFee == 0 ? order.estimateFee : order.actualFee, (int)order.skuNum);
else
itempoint = db.FindItemPoint(member, order.actualFee == 0 ? order.estimateFee : order.actualFee, (int)order.skuNum, CpsType.);
if (itempoint != null)
{
order.db_point = HttpHelper.ObjectToJson(itempoint);
order.db_userpoint = itempoint.UserPoint;
}
#endregion
if (member != null)
{
member.bind_order++;
member = db.UpdateMemberGroup(member);
}
#region
var record = db.FindStatisticsRecord(member.id);
if (record == null)
{
record = new fl_statistics_record() { uid = member.id, ex2 = 0, ex4 = HttpExtend.GetTimeStamp(DateTime.Now), ex5 = HttpExtend.GetTimeStamp(order.orderTime) };
db.Saveable<fl_statistics_record>(record).ExecuteCommand();
}
else
{
if (record.ex2 == 0 && record.ex4 == 0)
record.ex4 = HttpExtend.GetTimeStamp(DateTime.Now);
record.ex5 = HttpExtend.GetTimeStamp(order.orderTime);
db.Saveable<fl_statistics_record>(record).ExecuteCommand();
}
#endregion
db.SaveOrUpdate(order);
downJingdongTimer.UpdateOrder(order, db, notices, isFrontData: true);
}
}
#endregion
#region
if (!ApiClient.Setting.SystemConfig.message_warning_switch && notices.Count != 0)
{
var tasks = TimerTask.GetTimer<Update_NoticeQueue>() as Update_NoticeQueue;
foreach (var item in notices)
{
//if (item.IsRewards)
tasks.Add(item);
//else
//SDK_OrderNoticeEvent(this, item);
}
}
#endregion
e.Cancel = true;
}
else
{
e.SendMessage(Config.NotFoundOrderErrorTip.Replace("[订单号]", orderId));
//加入缓存
var bind = db.FindBindCache(orderId);
if (bind == null)
{
db.Insertable(new fl_bind_cache() { crt_time = DateTime.Now, db_robotid = e.RobotInfo.id, orderid = orderId, groupid = e.Groupid, db_userid = member.id }).ExecuteCommand();
db.FindBindCache(orderId, true);
}
e.Cancel = true;
return;
}
}
if (OrderHelper.IsOrderId(e.Message.Trim()))
return;
#endregion
compute = null;
#region
var jdinfoTemps = db.FindJdInfoTempGroups();
var jdInfoTemp = jdinfoTemps.FirstOrDefault(f => f.name == e.RobotInfo.name && f.onoff == false);
if (jdInfoTemp != null)
{
#region
string QRCodeUrl = string.Empty;
if (Config.QRCodeSearchSwitch == SwitchType.)
{
var reg_ = Regex.Match(e.Message, @"\[图片=(?<二维码图片>.+?)\]");
if (reg_.Success)
QRCodeUrl = Util.DecodeQRCode(reg_.Groups["二维码图片"].Value);//解析的二维码图片所得到的二维码内容
}
#endregion
var itemId = JDHelper.GetJingdongItemId(string.IsNullOrEmpty(QRCodeUrl) ? e.Message : QRCodeUrl);//匹配京东链接获取京东宝贝ID
//this.OnLog($"京东商品编码:{itemId}");
if (!string.IsNullOrEmpty(itemId))
{
JingdongApi api = null;
fl_cps_member jd_cps = null;
var pid = string.Empty;
var isDefault = true;
if (!string.IsNullOrWhiteSpace(e.Groupid))//群pid
{
var groupAdzone = db.FindAdzoneInfos().FirstOrDefault(f => f.alliance_id == (int)CpsType. && f.custom_type == PrivateAdzoneCustomType.pid.ToString() && f.group_id == e.Groupid);
if (groupAdzone != null && !string.IsNullOrWhiteSpace(groupAdzone.adzone_pid))
{
pid = groupAdzone.adzone_pid;
jd_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType. && f.username == groupAdzone.adzone_pid_cps_name);
isDefault = false;
}
}
if (isDefault)//私人pid
{
var memberAdzone = db.FindAdzoneInfos().FirstOrDefault(f => f.alliance_id == (int)CpsType. && f.custom_type == PrivateAdzoneCustomType.pid.ToString() && f.member_id == member.id);
if (memberAdzone != null && !string.IsNullOrWhiteSpace(memberAdzone.adzone_pid))//私人推广位
{
pid = memberAdzone.adzone_pid;
jd_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType. && f.username == memberAdzone.adzone_pid_cps_name);
isDefault = false;
}
}
if (isDefault)//默认推广位
{
pid = (member.buy_point >= Config.Point && member.finish_order >= Config.OrderNum) ? jdInfoTemp.pid_chief : jdInfoTemp.pid_deputy;
jd_cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType. && f.username == ((member.buy_point >= Config.Point && member.finish_order >= Config.OrderNum) ? jdInfoTemp.pid_chief_cps_name : jdInfoTemp.pid_deputy_cps_name));//通过判断用户的购物积分,来判断用户使用哪个推广位
}
if (jd_cps == null) { this.OnLog("京东联盟推广位异常,请检测后重试!"); return; }
api = new JingdongApi(jd_cps);
if (!ApiClient.Setting.SystemConfig.message_warning_switch)
e.SendMessage(Config.SearchingTip);//正在搜索提示
var goodInfoResult = api.SendJingdong("jd.union.open.goods.query", new { goodsReqDTO = new { skuIds = new long[] { long.Parse(itemId) } } });
var goodData = goodInfoResult.ConvertToObj<goodInfo_temp>();
if (goodData.data == null) throw new Exception("京东无返利信息");
foreach (Dictionary<string, object> _goodinfo in goodData.data)
{
var goodinfo = _goodinfo.ConvertToObj<GoodsResp>();
goodName = goodinfo.skuName = goodinfo.skuName.Replace("", "").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&").Replace("&quot;", "\"").Replace(" &copy;", "©");
if (goodinfo.commissionInfo.Count != 0)//有佣金
{
var isJdSale = goodinfo.isJdSale == 0 ? false : true;//是否已是京东自营
double price = double.Parse(goodinfo.priceInfo["price"].ToString()); //商品价格
double lowestPrice = double.Parse(goodinfo.priceInfo["lowestPrice"].ToString()); //商品促销价格
var commissionshare = decimal.Parse(goodinfo.commissionInfo["commissionShare"].ToString()) / 100m;//普通用户佣金比例 ,通用接口中的佣金比例
#region ,,
try
{
var goodResult = api.SendJingdong("jd.union.open.goods.promotiongoodsinfo.query", new { skuIds = itemId });
if (goodResult != null && goodResult.ContainsKey("data"))
{
var _goodData = goodResult["data"] as ArrayList;
if (_goodData != null && _goodData.Count != 0)
{
foreach (Dictionary<string, object> data in _goodData)
{
if (data.ContainsKey("commisionRatioWl"))
{
commissionshare = decimal.Parse(data["commisionRatioWl"].ToString()) / 100m; //接口中该商品的实际佣金,比较准一些,
break;
}
}
}
}
}
catch (Exception)
{ }
#endregion
#region plus用户的佣金比例 commissionshare_plus
// decimal commissionshare_plus = 0m; //plus会员佣金比例
// int i = 0;
//Next:
// try
// {
// var http = new HttpHelper();
// var item = new HttpItem();
// item.URL = @"https://union.jd.com/api/help/getCategoryCommiPlus?level=3&parentId= " + goodinfo.categoryInfo["cid2"].ToString();
// var reuslt = http.GetHtml(item);
// var jsonObj = HttpExtend.JsonToDictionary(reuslt.Html);
// if (jsonObj["code"].ToString() == "200")
// {
// if (jsonObj.ContainsKey("data"))
// {
// var cid3 = goodinfo.categoryInfo["cid3"].ToString();
// if (jsonObj.ContainsKey("data"))
// {
// var data = jsonObj["data"] as ArrayList;
// foreach (Dictionary<string, object> obj in data)
// {
// if (obj["id"].ToString() == cid3)
// {
// //goodinfo.owner //g=自营p=pop
// if (goodinfo.owner == "g")
// commissionshare_plus = decimal.Parse(obj["selfMobileComm"].ToString());
// else
// commissionshare_plus = decimal.Parse(obj["popMobileComm"].ToString());
// commissionshare_plus = commissionshare_plus / 100;
// break;
// }
// }
// }
// }
// }
// }
// catch (Exception ex)
// {
// this.OnLog(ex.Message);
// if (i <= 2)
// {
// i++;
// goto Next;
// }
// }
#endregion
//原价的佣金
ItemPoint usecoupon_commfee = null;//普通用户 用优惠券后积分信息
//ItemPoint usecoupon_commfee_plus = null;//plus用户 用优惠券后积分信息
//促销价的佣金
ItemPoint usecoupon_commfee_lowest = null;
double discount = -1; //优惠券金额
List<coupon> coupons = new List<coupon>();//优惠券信息
if (goodinfo.couponInfo.Count != 0)
{
var couponList = goodinfo.couponInfo["couponList"] as ArrayList;
if (couponList.Count != 0)//有优惠券
{
Compute compute0 = null;
Compute compute_lowest = null;
foreach (Dictionary<string, object> coupon in couponList)
{
ItemPoint _usecoupon_commfee = null;
//普通
{
var quota = double.Parse(coupon["quota"].ToString()); //券消费限额
if (quota <= price) //break;//优惠券面额大于商品单价时终止
{
discount = double.Parse(coupon["discount"].ToString());//券面额
#region
decimal usecoupon_totalcommfee = decimal.Round(((decimal)price - (decimal)discount) * commissionshare, 2);//券后 总佣金(自营)
if (!isJdSale)
usecoupon_totalcommfee = decimal.Round(usecoupon_totalcommfee * 0.9m, 2);//券后 总佣金(非自营)
_usecoupon_commfee = db.FindItemPoint(member, (double)usecoupon_totalcommfee, 1, CpsType., out compute0);//用券后 给用户的佣金
#endregion
#region plus用户
//var usecoupon_totalcommfee_plus = decimal.Round(((decimal)price - (decimal)discount) * commissionshare_plus, 2);//plus 券后 总佣金(自营)
//if (!isJdSale)
// usecoupon_totalcommfee_plus = decimal.Round(usecoupon_totalcommfee_plus * 0.9m,2);//券后 总佣金(非自营)
//usecoupon_commfee_plus = session.FindItemPoint(member, (double)usecoupon_totalcommfee_plus, 1, CpsType.京东联盟);//plus 用券后 给用户的佣金
#endregion
}
}
ItemPoint _usecoupon_commfee_lowest = null;
//促销
{
var quota = double.Parse(coupon["quota"].ToString()); //券消费限额
if (quota <= lowestPrice) //break;//优惠券面额大于商品单价时终止
{
discount = double.Parse(coupon["discount"].ToString());//券面额
#region
decimal usecoupon_totalcommfee = decimal.Round(((decimal)lowestPrice - (decimal)discount) * commissionshare, 2);//券后 总佣金(自营)
if (!isJdSale)
usecoupon_totalcommfee = decimal.Round(usecoupon_totalcommfee * 0.9m, 2);//券后 总佣金(非自营)
_usecoupon_commfee_lowest = db.FindItemPoint(member, (double)usecoupon_totalcommfee, 1, CpsType., out compute_lowest);//用券后 给用户的佣金
#endregion
}
}
if (_usecoupon_commfee_lowest != null || _usecoupon_commfee != null)
{
coupons.Add(new Class1.coupon() { couponlike = coupon["link"].ToString(), discount = discount, isBest = int.Parse(coupon["isBest"].ToString()), usecoupon_commfee = _usecoupon_commfee, usecoupon_commfee_lowest = _usecoupon_commfee_lowest, compute_lowest = compute_lowest, compute = compute0 });
}
}
}
}
var buyshorturl = string.Empty; //转连后的地址
#region (广 [()])
Dictionary<string, object> conversionlinkresult = null; //查询到的转换链接对象
var positionId = pid.Substring(pid.LastIndexOf("_") + 1);
//var custom = $"p_{positionId}_r_{e.RobotName}_u_{e.GetMemberinfo().username}_gid_{itemId}";
if (coupons.Count != 0)
{
coupons = coupons.OrderByDescending(s => s.isBest).ToList<coupon>();
for (int i = 0; i < coupons.Count; i++)
{
try
{
conversionlinkresult = api.SendJingdong("jd.union.open.promotion.byunionid.get", new { promotionCodeReq = new { materialId = $@"https://item.m.jd.com/product/{itemId}.html", positionId = positionId, unionId = jd_cps.usernick, couponUrl = coupons[i].couponlike, chainType = 3/*, subUnionId = custom*/ } });
discount = coupons[i].discount;
usecoupon_commfee = coupons[i].usecoupon_commfee;
usecoupon_commfee_lowest = coupons[i].usecoupon_commfee;
compute = coupons[i].compute ?? coupons[i].compute_lowest;
break;
}
catch (Exception ex)
{
discount = -1;
conversionlinkresult = null;
compute = null;
continue;
}
}
}
if (coupons.Count == 0 || conversionlinkresult == null)
{
conversionlinkresult = api.SendJingdong("jd.union.open.promotion.byunionid.get", new { promotionCodeReq = new { materialId = $@"https://item.m.jd.com/product/{itemId}.html", positionId = positionId, unionId = jd_cps.usernick, chainType = 3/*, subUnionId = custom*/ } });//宝贝id 和 用户的目标推客的联盟id
}
if (conversionlinkresult != null)
{
#region id查询接口返回的json样式 #
/*
//没有返利的样式
{
result: {
apicodeenum: "user_unionid_err",
code: 411,
message: "unionid不正确请检查unionid是否正确",
requestid: "21922_0b12a2ef_jul5xdgr_4036450"
},
code: "0"
}
//有返利的样式
{
result: {
code: 200,
data: {
shorturl: "https://u.jd.com/q6xkht"
},
message: "success",
requestid: "21922_0ab504e9_jul5xy3v_4135009"
},
code: "0"
}
*/
#endregion
if (conversionlinkresult["code"].ToString() != "200") throw new Exception($"京东查询接口调用失败:{conversionlinkresult["message"].ToString()}");//抛出错误信息
if (conversionlinkresult.ContainsKey("data"))
{
var data = conversionlinkresult["data"] as Dictionary<string, object>;
if (data.ContainsKey("shortURL")) buyshorturl = data["shortURL"].ToString();//购买短连接
}
if (string.IsNullOrWhiteSpace(buyshorturl)) throw new Exception("京东转链失败,请稍后重试");
}
#endregion
#region
Compute computeTmp = null;
//不用券 佣金
var unusecoupon_totalcommfee = decimal.Round((decimal)price * commissionshare, 2);//券后 总佣金(自营)
if (!isJdSale)
unusecoupon_totalcommfee = decimal.Round(unusecoupon_totalcommfee * 0.9m, 2);//券后 总佣金(非自营)
//不用券 给用户的佣金
var unusecoupon_commfee = db.FindItemPoint(member, (double)unusecoupon_totalcommfee, 1, CpsType., out computeTmp);
if (compute == null)
compute = computeTmp;
#endregion
#region
//不用券 佣金
var unusecoupon_totalcommfee_lowest = decimal.Round((decimal)lowestPrice * commissionshare, 2);//券后 总佣金(自营)
if (!isJdSale)
unusecoupon_totalcommfee_lowest = decimal.Round(unusecoupon_totalcommfee_lowest * 0.9m, 2);//券后 总佣金(非自营)
//不用券 给用户的佣金
var unusecoupon_commfee_lowest = db.FindItemPoint(member, (double)unusecoupon_totalcommfee_lowest, 1, CpsType., out computeTmp);
if (compute == null)
compute = computeTmp;
#endregion
#region Plus用户
//plus 不用券 佣金
//var unusecoupon_totalcommfee_plus = decimal.Round((decimal)price * commissionshare_plus, 2);//券后 总佣金(自营)
//if (!isJdSale)
// unusecoupon_totalcommfee_plus = decimal.Round(unusecoupon_totalcommfee_plus * 0.9m,2);//券后 总佣金(非自营)
//plus 不用券 给用户的佣金
//var unusecoupon_commfee_plus = session.FindItemPoint(member, (double)unusecoupon_totalcommfee_plus, 1, CpsType.京东联盟);
#endregion
var imageList = goodinfo.imageInfo["imageList"] as ArrayList;
string imageUrl = string.Empty;
if (imageList.Count > 0)
imageUrl = (imageList[0] as Dictionary<string, object>)["url"].ToString(); //宝贝主图
if (discount != -1) //有券的情况
{
var mess = string.Empty;
if (e.ChatType == ChatType. || e.ChatType == ChatType. || (e.ChatType == ChatType.QQ && string.IsNullOrWhiteSpace(Config.QQSearchSuccessWithCouponTip)))
mess = Config.SearchSuccessWithCouponTip;
else
mess = Config.QQSearchSuccessWithCouponTip;
e.SendMessage(mess
.Replace("劵", "券")
.Replace("[商品标题]", goodinfo.skuName)
.Replace("[商品原价]", goodinfo.priceInfo["price"].ToString())
.Replace("[商品主图]", $"[图片={imageUrl}]")
.Replace("[图片地址]", imageUrl)
.Replace("[月销量]", goodinfo.inOrderCount30Days.ToString())
.Replace("[券后返利]", usecoupon_commfee.UserPoint.ToString())
.Replace("[弃券返利]", unusecoupon_commfee.UserPoint.ToString())
//.Replace("[会员券后返利]", usecoupon_commfee_plus.UserPoint.ToString())
//.Replace("[会员弃券返利]", unusecoupon_commfee_plus.UserPoint.ToString())
.Replace("[券后价]", ((decimal)price - (decimal)discount).ToString())
.Replace("[优惠券金额]", string.Format("{0:F}", discount))
.Replace("[购买地址]", buyshorturl)
.Replace("[共节省]", ((decimal)discount + (decimal)usecoupon_commfee.UserPoint).ToString())
.Replace("[商品促销价]", string.Format("{0:F}", lowestPrice))
.Replace("[促销价返利]", ((decimal)usecoupon_commfee_lowest.UserPoint).ToString())
.Replace("[促销券后价]", ((decimal)lowestPrice - (decimal)discount).ToString())
.Replace("[促销共节省]", (usecoupon_commfee_lowest == null ? ((decimal)discount + (decimal)usecoupon_commfee.UserPoint).ToString() : ((decimal)discount + (decimal)usecoupon_commfee_lowest.UserPoint).ToString()))
.Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(goodinfo.skuName, price.ToString(), discount.ToString(), ((decimal)price - (decimal)discount).ToString(), imageUrl, buyshorturl, ApiClient.QrImageType.B, CpsType.) + "]" : string.Empty));
}
else
{
var mess = string.Empty;
if (e.ChatType == ChatType. || e.ChatType == ChatType. || (e.ChatType == ChatType.QQ && string.IsNullOrWhiteSpace(Config.QQSearchSuccessWithoutCouponTip)))
mess = Config.SearchSuccessWithoutCouponTip;
else
mess = Config.QQSearchSuccessWithoutCouponTip;
e.SendMessage(mess.Replace("[商品标题]", goodinfo.skuName)
.Replace("[商品原价]", goodinfo.priceInfo["price"].ToString())
.Replace("[商品主图]", $"[图片={imageUrl}]")
.Replace("[图片地址]", imageUrl)
.Replace("[月销量]", goodinfo.inOrderCount30Days.ToString())
.Replace("[返利积分]", string.Format("{0:F}", unusecoupon_commfee.UserPoint))
//.Replace("[会员返利积分]", (unusecoupon_commfee_plus.UserPoint).ToString())
.Replace("[购买地址]", buyshorturl)
.Replace("[共节省]", string.Format("{0:F}", unusecoupon_commfee.UserPoint))
.Replace("[商品促销价]", string.Format("{0:F}", lowestPrice))
.Replace("[促销价返利]", ((decimal)unusecoupon_commfee_lowest.UserPoint).ToString())
.Replace("[商品图片]", mess.Contains("[商品图片]") ? "[图片=" + ApiClient.GetQRImage(goodinfo.skuName, price.ToString(), "0", price.ToString(), imageUrl, buyshorturl, ApiClient.QrImageType.B, CpsType.) + "]" : string.Empty)
);
}
#region ,,,
db.Insertable(new fl_query_hist()
{
crt_time = DateTime.Now,
type = CpsType.,
itemid = itemId,
groupid = e.Groupid,
robot_name = e.RobotName,
robot_type = e.ChatType,
userid = member.id,
title = goodinfo.skuName,
adzoneid = positionId,
compute_configdic = compute == null ? string.Empty : JsonConvert.SerializeObject(compute)
}).ExecuteCommand();
db.UpdateRecord(member.id);
var shared = new Dictionary<string, object>();
shared["msg_type"] = "查询宝贝";
shared["cps_type"] = CpsType.;
shared["msg_username"] = member.username;
shared["price"] = string.Format("{0:F}", lowestPrice);
shared["title"] = goodName;
shared["coupon_price"] = string.Format("{0:F}", (discount != -1 ? discount : 0));
shared["user_point"] = discount != -1 ? string.Format("{0:F}", usecoupon_commfee_lowest.UserPoint) : string.Format("{0:F}", unusecoupon_commfee_lowest.UserPoint);
shared["economize"] = string.Format("{0:F}", (discount != -1 ? (usecoupon_commfee_lowest == null ? ((decimal)discount + (decimal)usecoupon_commfee.UserPoint) : ((decimal)discount + (decimal)usecoupon_commfee_lowest.UserPoint)) : (decimal)unusecoupon_commfee_lowest.UserPoint));
var sharedEvent = new SharedEvents(shared);
EventClient.OnEvent(sender, sharedEvent);
#endregion
}
}
}
}
#endregion
}
catch (Exception ex)
{
if (ex.Message.Contains("商品不在推广中") || ex.Message.StartsWith("京东")) //自己抛出的错误,以京东开头
{
e.SendMessage(Config.SearchNoCommissionTip); //提示没有返利提示
var session = ApiClient.GetSession();
session.UpdateRecord(e.GetMemberinfo().id);
var shared = new Dictionary<string, object>();
shared["msg_type"] = "查询宝贝";
shared["cps_type"] = CpsType.;
shared["msg_username"] = e.GetMemberinfo().username;
shared["price"] = "未知";
shared["title"] = goodName;
shared["coupon_price"] = "未知";
shared["user_point"] = "未知";
shared["economize"] = "未知";
var sharedEvent = new SharedEvents(shared);
EventClient.OnEvent(sender, sharedEvent);
return;
}
this.OnLog($"{ex.Message},{ex.StackTrace}");
e.SendMessage(ApiClient.Setting.SystemConfig.msg_error);
}
}
/// <summary>
/// 订单状态 提示语替换
/// </summary>
/// <param name="order"></param>
/// <param name="objs"></param>
/// <returns></returns>
private string _GetOrderStateMess(SystemOrderStatus order, SettleType settle, params object[] objs)
{
var mess = string.Empty;
switch (order)
{
case SystemOrderStatus.:
mess = new VariateReplace().CommonReplace(Config.OrderPaymentTip, objs);
break;
case SystemOrderStatus.:
mess = new VariateReplace().CommonReplace(Config.OrderFailureTip, objs);
break;
case SystemOrderStatus.退:
mess = new VariateReplace().CommonReplace(Config.OrderFrozen_AllTip, objs);
break;
case SystemOrderStatus.:
mess = new VariateReplace().CommonReplace(Config.OrderRefundTip, objs);
break;
case SystemOrderStatus.:
mess = new VariateReplace().CommonReplace(settle == SettleType. ? Config.OrderSettlementTip : Config.OrderAlreadySettlementTip, objs);
break;
case SystemOrderStatus.:
mess = new VariateReplace().CommonReplace(Config.OrderFreezeTip, objs);
break;
}
return mess;
}
private class coupon
{
//优惠券链接
public string couponlike { get; set; }
//券面额
public double discount { get; set; }
//最优优惠券10
public int isBest { get; set; }
//分出佣金积分信息
public ItemPoint usecoupon_commfee { get; set; }
/// <summary>
/// 促销分出佣金积分信息
/// </summary>
public ItemPoint usecoupon_commfee_lowest { get; set; }
/// <summary>
/// 计算佣金的比例数据
/// </summary>
public Compute compute { get; set; }
/// <summary>
/// 促销计算佣金的比例数据
/// </summary>
public Compute compute_lowest { get; set; }
}
}
}