orders.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. .Save();
  155. throw response.ResponseException;
  156. }
  157. var body = response.Body();
  158. JsonElement data;
  159. try
  160. {
  161. var root = body.Convert2JsonElement();
  162. var succss = root.Read<bool>("success");
  163. data = root.ElementRead("data");
  164. if (!succss)
  165. {
  166. throw new APIException(body);
  167. }
  168. }
  169. catch (Exception ex)
  170. {
  171. throw new APIException(body);
  172. }
  173. using var conn = DBContext.GetOpenConnection();
  174. conn.Open();
  175. try
  176. {
  177. foreach (var order in data.ElementRead("result").EnumerateArray())
  178. {
  179. TkOrderDetailDTO item = order.GetRawText().Convert2Object<TkOrderDetailDTO>();
  180. // 处理每个订单数据
  181. item.accountId = _accountId;
  182. item.accountName = _company;
  183. if (item.modifiedTime > max_modifiedTime) max_modifiedTime = item.modifiedTime;
  184. if (last_modifiedTime != DateTime.MinValue && last_modifiedTime >= item.modifiedTime)
  185. {
  186. return (total, max_modifiedTime, orderTimes);
  187. }
  188. //进行订单和转链匹配
  189. //string mktItemLink = $"https:{item.mktItemLink}";
  190. //item.itemId = GetRawItemId(mktItemLink);
  191. if (item.tkStatus == 3 && item.tbPaidTime != DateTime.MinValue) orderTimes.Add(item.tbPaidTime.Date);
  192. int? id = conn.Replace(item);
  193. if (id != null)
  194. {
  195. item.id = (int)id;
  196. TkOrderTrackingCore.MatchOrder(item, conn);
  197. }
  198. total++;
  199. }
  200. }
  201. catch (Exception ex)
  202. {
  203. throw;
  204. }
  205. finally
  206. {
  207. conn.Dispose();
  208. }
  209. pageNo++;
  210. hasNext = data.Read<bool>("hasNext");
  211. positionIndex = data.Read<string>("positionIndex");
  212. if (sleep > 0) Thread.Sleep(sleep);
  213. }
  214. return (total, max_modifiedTime, orderTimes);
  215. }
  216. string GetRawItemId(string url)
  217. {
  218. try
  219. {
  220. string cacheKey = $":cache:url2itemId:{url}";
  221. string itemId = RedisHelper.Get(cacheKey);
  222. if (itemId != null) return itemId;
  223. WebClientUtility client = new()
  224. {
  225. Proxy = _proxy,
  226. UserAgent = Sayaka.Common.ProviderFakeUserAgent.RandomComputer
  227. };
  228. #if DEBUG
  229. client.Proxy = null;
  230. #endif
  231. client.AllowAutoRedirect = false;
  232. var response = client.Request(url);
  233. if (response.Successed)
  234. {
  235. string location = response.ResponseMessage?.Headers?.Location?.ToString();
  236. if (!string.IsNullOrEmpty(location))
  237. {
  238. itemId = location.GetContentPart("id=", "");
  239. if (!string.IsNullOrEmpty(itemId))
  240. {
  241. RedisHelper.Set(cacheKey, itemId, 86400 * 30);
  242. }
  243. return itemId;
  244. }
  245. var responseBody = response.Body();
  246. if (response.ResponseMessage.IsSuccessStatusCode)
  247. {
  248. throw new APIException(responseBody);
  249. }
  250. else
  251. {
  252. throw new APIException($"{response.ResponseMessage.StatusCode}\t{responseBody}");
  253. }
  254. }
  255. else
  256. {
  257. throw response.ResponseException;
  258. }
  259. }
  260. catch (Exception ex)
  261. {
  262. string message = $"【GetRawItemId】[{url}\n{ex.Message}\n{ex.StackTrace}";
  263. NotifyCore.Notify(new NifyMessage
  264. {
  265. message = message,
  266. priority = NifyMessagePriority.high,
  267. tags = ["red_circle"]
  268. });
  269. }
  270. return null;
  271. }
  272. public void GetTkOrders222()
  273. {
  274. try
  275. {
  276. string url = "https://media.alimama.com/violationu2/warning_instance_page_v2.json?r=mx_208&toPage=1&pageSize=40&params=";
  277. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  278. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  279. .AddHeaders("Cookie", _cookies);
  280. client.Proxy = _proxy;
  281. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  282. var response = client.Request(url);
  283. var body = response.Body();
  284. var root = body.Convert2JsonElement();
  285. int resultCode = root.Read<int>("resultCode", 0);
  286. int totalCount = root.PathRead<int>("data.totalCount", 0);
  287. bool success = root.Read("success", false);
  288. if (!success)
  289. {
  290. new LoggerLibrary("violationu", "warning_error")
  291. .Info(url, body)
  292. .Save();
  293. throw new Exception(body);
  294. }
  295. if (totalCount == 0) return;
  296. new LoggerLibrary("violationu", "warning").Info(url, body).Save();
  297. var list = root.ElementRead("data").ElementRead("result").EnumerateArray();
  298. foreach (var data in list)
  299. {
  300. var violation_commission = data.PathRead<decimal>("mediaInfo.订单虚假交易违规佣金", 0);
  301. new DBContext.Table("alimama_warning")
  302. .Fill(data)
  303. .Loader<int>("filterRuleId", 0)
  304. .Loader<long>("gmtCreate", 0)
  305. .Loader<long>("id", 0, "ali_id")
  306. .Loader<string>("idStr", string.Empty)
  307. .Loader<int>("mediaDimension", 0)
  308. .Loader<long>("mediaId", 0)
  309. .Loader<int>("mediaInfo.abn_cnt", 0, "abn_cnt")
  310. .Add("violation_commission", violation_commission)
  311. .Loader<int>("mediaInfo.warning_cnt", 0, "warning_cnt")
  312. .Loader<string>("mediaName", string.Empty)
  313. .Loader<long>("memberId", 0)
  314. .Loader<string>("noticeCategory", string.Empty)
  315. .Loader<int>("noticeTemplateId", 0)
  316. .Loader<string>("noticeTemplateName", string.Empty)
  317. .Loader<string>("orderFile", string.Empty)
  318. .Loader<string>("pid", string.Empty)
  319. .Loader<int>("punishRuleId", 0)
  320. .Loader<string>("riskType", string.Empty)
  321. .Loader<string>("roleName", string.Empty)
  322. .Loader<string>("ruleLink", string.Empty)
  323. .Loader<bool>("showOrderDetail", false)
  324. .Loader<int>("status", 0, "ali_status")
  325. .Loader<string>("warningText", string.Empty)
  326. .Add("accountName", _accountName)
  327. .Add("status", true)
  328. .Add("create_time", DateTime.Now)
  329. .Add("last_time", DateTime.Now)
  330. .Create(DBContext.InsertType.REPLACE);
  331. }
  332. }
  333. catch (Exception ex) { }
  334. }
  335. }
  336. }