orders.cs 15 KB

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