orders.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. using dodohold.core;
  2. using Spire.Pdf.Xmp;
  3. using System.Data;
  4. using System.Drawing.Printing;
  5. using System.Runtime.InteropServices;
  6. using System.Text.Json;
  7. using System.Text.RegularExpressions;
  8. namespace molilian.core
  9. {
  10. public partial class AlimamaPlus
  11. {
  12. private const string base_orders_url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/report.getTbkOrderDetails.json";
  13. public int GetHistoryOrders(int sleep)
  14. {
  15. DateTime endTime = DateTime.Now;
  16. DateTime startTime = endTime.AddDays(-90);
  17. ////找出数据库最新的一天
  18. //var last = new DBContext.Table("tk_order_details")
  19. // .Order("modifiedTime DESC")
  20. // .Get<TkOrderDetailDTO>("accountId=@accountId", new { accountId = _accountId });
  21. //if (last != null)
  22. //{
  23. // startTime = last.modifiedTime;
  24. //}
  25. //当日往前查询
  26. (int total, _, _) = GetTkOrders(startTime, endTime, DateTime.MinValue, false, sleep);
  27. return total;
  28. }
  29. public int GetIncyOrders(int sleep)
  30. {
  31. string cacheKey = $":cache:GetIncyOrders:{_accountName}";
  32. DateTime endTime = DateTime.Now;
  33. DateTime startTime = endTime.AddDays(-1);
  34. DateTime last_modifiedTime = RedisHelper.Get<DateTime>(cacheKey);
  35. ////找出数据库最新的一天
  36. //var last = new DBContext.Table("tk_order_details")
  37. // .Order("modifiedTime DESC")
  38. // .Get<TkOrderDetailDTO>("accountId=@accountId", new { accountId = _accountId });
  39. if (last_modifiedTime != DateTime.MinValue)
  40. {
  41. startTime = last_modifiedTime;
  42. }
  43. else
  44. {
  45. last_modifiedTime = startTime;
  46. }
  47. //当日往前查询
  48. (int total, DateTime max_modifiedTime, List<DateTime> orderTimes) = GetTkOrders(startTime, endTime, last_modifiedTime, true, sleep);
  49. if (max_modifiedTime != DateTime.MinValue)
  50. {
  51. RedisHelper.Set(cacheKey, max_modifiedTime);
  52. }
  53. //todo 根据orderTimes、settlementTimes 更新被影响的相关行
  54. /*
  55. UPDATE tk_report tr
  56. JOIN (
  57. SELECT
  58. accountId,
  59. DATE(tbPaidTime) AS date,
  60. SUM(alipayTotalPrice) AS order_ord_amt,
  61. SUM(pubShareFeeForCommission) AS order_ord_tfee
  62. FROM tk_order_details
  63. WHERE tkStatus=3
  64. GROUP BY DATE(tbPaidTime), accountId
  65. ) AS sub
  66. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  67. SET tr.order_ord_amt = sub.order_ord_amt,
  68. tr.order_ord_tfee = sub.order_ord_tfee;
  69. */
  70. string sql = @"
  71. UPDATE tk_report tr
  72. JOIN (
  73. SELECT
  74. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt, SUM(pubShareFeeForCommission) AS order_ord_tfee
  75. FROM tk_order_details
  76. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=3
  77. GROUP BY DATE(tbPaidTime), accountId
  78. ) AS sub
  79. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  80. SET tr.order_ord_amt = sub.order_ord_amt, tr.order_ord_tfee = sub.order_ord_tfee;";
  81. DBContext.Execute(sql, new { orderTimes });
  82. sql = @"
  83. UPDATE tk_report tr
  84. JOIN (
  85. SELECT
  86. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  87. FROM tk_order_details
  88. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=12
  89. GROUP BY DATE(tbPaidTime), accountId
  90. ) AS sub
  91. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  92. SET tr.order_ord_amt_12 = sub.order_ord_amt, tr.order_ord_tfee_12 = sub.order_ord_tfee;";
  93. DBContext.Execute(sql, new { orderTimes });
  94. sql = @"
  95. UPDATE tk_report tr
  96. JOIN (
  97. SELECT
  98. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  99. FROM tk_order_details
  100. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=13
  101. GROUP BY DATE(tbPaidTime), accountId
  102. ) AS sub
  103. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  104. SET tr.order_ord_amt_13 = sub.order_ord_amt, tr.order_ord_tfee_13 = sub.order_ord_tfee;";
  105. DBContext.Execute(sql, new { orderTimes });
  106. sql = @"
  107. UPDATE tk_report tr
  108. JOIN (
  109. SELECT
  110. accountId, DATE(tbPaidTime) AS date, SUM(alipayTotalPrice) AS order_ord_amt, SUM(pubSharePreFeeForCommission) AS order_ord_tfee
  111. FROM tk_order_details
  112. WHERE DATE(tbPaidTime) IN @orderTimes AND tkStatus=14
  113. GROUP BY DATE(tbPaidTime), accountId
  114. ) AS sub
  115. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  116. SET tr.order_ord_amt_14 = sub.order_ord_amt, tr.order_ord_tfee_14 = sub.order_ord_tfee;";
  117. DBContext.Execute(sql, new { orderTimes });
  118. return total;
  119. }
  120. public (int, DateTime, List<DateTime>) GetTkOrders(DateTime startTime, DateTime endTime, DateTime last_modifiedTime, bool desc = true, int sleep = 100)
  121. {
  122. List<DateTime> orderTimes = [];
  123. // 确保 startTime 小于 endTime
  124. if (startTime > endTime)
  125. {
  126. (startTime, endTime) = (endTime, startTime);
  127. }
  128. DateTime max_modifiedTime = last_modifiedTime;
  129. int pageNo = 1;
  130. string positionIndex = string.Empty;
  131. int pageSize = 100;
  132. bool hasNext = true;
  133. int total = 0;
  134. while (hasNext)
  135. {
  136. var ts = DateTime.Now.Convert2UnixTimestamp();
  137. //string jumpType = pageNo == 1 ? "0" : desc ? "1" : "-1";
  138. string jumpType = desc ? pageNo == 1 ? "0" : "1" : "-1";
  139. //string queryType = "1";
  140. string queryType = "4";
  141. string url = $"{base_orders_url}?t={ts}&_tb_token_={_tb_token}&pageNo={pageNo}&pageSize={pageSize}&startTime={startTime:yyyy-MM-dd}&endTime={endTime:yyyy-MM-dd}&payStatus=&queryType={queryType}&jumpType={jumpType}&tkTradeId=&positionIndex={positionIndex}";
  142. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  143. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  144. .AddHeaders("Cookie", _cookies);
  145. #if DEBUG
  146. #else
  147. client.Proxy = _proxy;
  148. #endif
  149. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  150. var response = client.Request(url);
  151. if (response.ResponseException != null)
  152. {
  153. _ = new LoggerLibrary("api_error", "fail")
  154. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  155. .SaveAsync();
  156. throw response.ResponseException;
  157. }
  158. var body = response.Body();
  159. JsonElement data;
  160. try
  161. {
  162. var root = body.Convert2JsonElement();
  163. var success = root.Read<bool>("success");
  164. data = root.ElementRead("data");
  165. //{"code":601,"info":{"ok":false,"message":"nologin"}}
  166. if (!success && body.Contains("nologin"))
  167. {
  168. (success, string message) = RenewCookie();
  169. if (!success)
  170. {
  171. TkPoolCore.Disabled(_accountId, _accountName, $"{body}");
  172. }
  173. return (0, DateTime.MinValue, new List<DateTime>());
  174. }
  175. if (!success)
  176. {
  177. throw new APIException(body);
  178. }
  179. }
  180. catch (Exception ex)
  181. {
  182. throw new APIException(body);
  183. }
  184. using var conn = DBContext.GetOpenConnection();
  185. conn.Open();
  186. try
  187. {
  188. foreach (var order in data.ElementRead("result").EnumerateArray())
  189. {
  190. TkOrderDetailDTO item = order.GetRawText().Convert2Object<TkOrderDetailDTO>();
  191. // 处理每个订单数据
  192. item.accountId = _accountId;
  193. item.accountName = _company;
  194. if (item.modifiedTime > max_modifiedTime) max_modifiedTime = item.modifiedTime;
  195. if (last_modifiedTime != DateTime.MinValue && last_modifiedTime >= item.modifiedTime)
  196. {
  197. return (total, max_modifiedTime, orderTimes);
  198. }
  199. //进行订单和转链匹配
  200. item.itemId = GetRawItemId(item.mktId);
  201. if (item.tkStatus == 3 && item.tbPaidTime != DateTime.MinValue) orderTimes.Add(item.tbPaidTime.Date);
  202. int? id = conn.Replace(item);
  203. if (id != null)
  204. {
  205. item.id = (int)id;
  206. TkOrderTrackingCore.MatchOrder(item, conn);
  207. }
  208. total++;
  209. }
  210. }
  211. catch (Exception ex)
  212. {
  213. throw;
  214. }
  215. finally
  216. {
  217. conn.Dispose();
  218. }
  219. pageNo++;
  220. hasNext = data.Read<bool>("hasNext");
  221. positionIndex = data.Read<string>("positionIndex");
  222. if (sleep > 0) Thread.Sleep(sleep);
  223. }
  224. return (total, max_modifiedTime, orderTimes);
  225. }
  226. string GetRawItemId(string mktId)
  227. {
  228. try
  229. {
  230. string cacheKey = $":cache:mkt2itemId:{mktId}";
  231. string itemId = RedisHelper.Get(cacheKey);
  232. if (itemId != null) return itemId;
  233. var ts = DateTime.Now.Convert2UnixTimestamp(true);
  234. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/union.moose.content.entry";
  235. //string url = $"{base_orders_url}?t={ts}&_tb_token_={_tb_token}&pageNo={pageNo}&pageSize={pageSize}&startTime={startTime:yyyy-MM-dd}&endTime={endTime:yyyy-MM-dd}&payStatus=&queryType={queryType}&jumpType={jumpType}&tkTradeId=&positionIndex={positionIndex}";
  236. var client = new WebClientUtility()
  237. .SetContentType("application/x-www-form-urlencoded")
  238. .AddHeaders("Cookie", _cookies)
  239. .AddHeaders("Origin", "https://pub.alimama.com")
  240. .Post("_tb_token_", _tb_token)
  241. .Post("t", ts.ToString())
  242. .Post("bizType", "detailPage")
  243. .Post("bizParam", $"{{\"itemId\":\"{mktId}\"}}");
  244. //_tb_token_=3b88755bbe3f7&t=1718896771391&bizType=detailPage&bizParam=%7B%22itemId%22%3A%22JbtMUqkGMQvagTNb2Fvta-9ag242pu7MOX5e0bsrY%22%7D
  245. //_tb_token_=361e383eb61e5&t=1718895935097&bizType=detailPage&bizParam=%7B%22itemId%22%3A%22JbtMUqkGMQvagTNb2Fvta-9ag242pu7MOX5e0bsrY%22%7D
  246. #if DEBUG
  247. #else
  248. client.Proxy = _proxy;
  249. #endif
  250. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  251. var response = client.Request(url);
  252. if (!response.Successed)
  253. {
  254. throw response.ResponseException;
  255. }
  256. var body = response.Body();
  257. var root = body.Convert2JsonElement();
  258. itemId = root.PathRead<string>("model.item.itemId");
  259. if (!string.IsNullOrEmpty(itemId))
  260. {
  261. RedisHelper.Set(cacheKey, itemId, 86400 * 7);
  262. }
  263. return itemId;
  264. }
  265. catch (Exception ex)
  266. {
  267. string message = $"【GetRawItemId】[{mktId}\n{ex.Message}\n{ex.StackTrace}";
  268. NotifyCore.Notify(new NifyMessage
  269. {
  270. message = message,
  271. priority = NifyMessagePriority.high,
  272. tags = ["red_circle"]
  273. });
  274. }
  275. return null;
  276. }
  277. public void GetTkOrders222()
  278. {
  279. try
  280. {
  281. string url = "https://media.alimama.com/violationu2/warning_instance_page_v2.json?r=mx_208&toPage=1&pageSize=40&params=";
  282. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  283. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  284. .AddHeaders("Cookie", _cookies);
  285. client.Proxy = _proxy;
  286. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  287. var response = client.Request(url);
  288. var body = response.Body();
  289. var root = body.Convert2JsonElement();
  290. int resultCode = root.Read<int>("resultCode", 0);
  291. int totalCount = root.PathRead<int>("data.totalCount", 0);
  292. bool success = root.Read("success", false);
  293. if (!success)
  294. {
  295. _ = new LoggerLibrary("violationu", "warning_error")
  296. .Info(url, body)
  297. .SaveAsync();
  298. throw new Exception(body);
  299. }
  300. if (totalCount == 0) return;
  301. _ = new LoggerLibrary("violationu", "warning").Info(url, body).SaveAsync();
  302. var list = root.ElementRead("data").ElementRead("result").EnumerateArray();
  303. foreach (var data in list)
  304. {
  305. var violation_commission = data.PathRead<decimal>("mediaInfo.订单虚假交易违规佣金", 0);
  306. new DBContext.Table("alimama_warning")
  307. .Fill(data)
  308. .Loader<int>("filterRuleId", 0)
  309. .Loader<long>("gmtCreate", 0)
  310. .Loader<long>("id", 0, "ali_id")
  311. .Loader<string>("idStr", string.Empty)
  312. .Loader<int>("mediaDimension", 0)
  313. .Loader<long>("mediaId", 0)
  314. .Loader<int>("mediaInfo.abn_cnt", 0, "abn_cnt")
  315. .Add("violation_commission", violation_commission)
  316. .Loader<int>("mediaInfo.warning_cnt", 0, "warning_cnt")
  317. .Loader<string>("mediaName", string.Empty)
  318. .Loader<long>("memberId", 0)
  319. .Loader<string>("noticeCategory", string.Empty)
  320. .Loader<int>("noticeTemplateId", 0)
  321. .Loader<string>("noticeTemplateName", string.Empty)
  322. .Loader<string>("orderFile", string.Empty)
  323. .Loader<string>("pid", string.Empty)
  324. .Loader<int>("punishRuleId", 0)
  325. .Loader<string>("riskType", string.Empty)
  326. .Loader<string>("roleName", string.Empty)
  327. .Loader<string>("ruleLink", string.Empty)
  328. .Loader<bool>("showOrderDetail", false)
  329. .Loader<int>("status", 0, "ali_status")
  330. .Loader<string>("warningText", string.Empty)
  331. .Add("accountName", _accountName)
  332. .Add("status", true)
  333. .Add("create_time", DateTime.Now)
  334. .Add("last_time", DateTime.Now)
  335. .Create(DBContext.InsertType.REPLACE);
  336. }
  337. }
  338. catch (Exception ex) { }
  339. }
  340. }
  341. }