RefundOrders.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. using dodohold.core;
  2. using System.Text.Json;
  3. namespace molilian.core
  4. {
  5. public partial class AlimamaPlus
  6. {
  7. private const string base_refund_orders_url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/report.publisher.getRefundOrderDetail.json";
  8. public async Task<int> GetHistoryRefundOrdersAsync(int sleep, DateTime startTime, DateTime endTime)
  9. {
  10. //DateTime endTime = DateTime.Now;
  11. //DateTime startTime = endTime.AddDays(-90);
  12. //if (_accountId == 3) endTime = DateTime.Parse("2024-04-07");
  13. //#if DEBUG
  14. // startTime = DateTime.Parse("2024-05-01");
  15. // endTime = DateTime.Parse("2024-06-01");
  16. // int total = 0;
  17. // List<DateTime> orderTimes = new List<DateTime>();
  18. // for (DateTime date = startTime; date <= endTime; date = date.AddDays(1))
  19. // {
  20. // orderTimes.Add(date);
  21. // }
  22. //#else
  23. //当日往前查询
  24. (int total, DateTime max_modifiedTime, List<DateTime> orderTimes) = await GetTkRefundOrdersAsync(startTime, endTime, DateTime.MinValue, false, sleep);
  25. //#endif
  26. if (_account.is_hide) return total;
  27. string sql = @"
  28. UPDATE tk_report tr
  29. JOIN (
  30. SELECT
  31. accountId, DATE(tbTradeCreateTime) AS date, SUM(refundFee) AS refund_order_ord_amt,
  32. COUNT(*) AS refund_order_ord_num, SUM(showReturnFee) AS refund_order_ord_tfee
  33. FROM tk_refund_order_details
  34. WHERE DATE(tbTradeCreateTime) IN @orderTimes AND refundStatus=2 AND accountId=@accountId
  35. GROUP BY DATE(tbTradeCreateTime), accountId
  36. ) AS sub
  37. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  38. SET tr.refund_order_ord_amt = sub.refund_order_ord_amt,
  39. tr.refund_order_ord_tfee = sub.refund_order_ord_tfee,
  40. tr.refund_order_ord_num = sub.refund_order_ord_num;";
  41. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  42. sql = @"
  43. UPDATE tk_report tr
  44. JOIN (
  45. SELECT
  46. accountId, DATE(tbTradeCreateTime) AS date, SUM(refundFee) AS refund_order_ord_amt,
  47. COUNT(*) AS refund_order_ord_num, SUM(showReturnFee) AS refund_order_ord_tfee
  48. FROM tk_refund_order_details
  49. WHERE DATE(tbTradeCreateTime) IN @orderTimes AND refundStatus=4 AND accountId=@accountId
  50. GROUP BY DATE(tbTradeCreateTime), accountId
  51. ) AS sub
  52. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  53. SET tr.refund_order_ord_amt_4 = sub.refund_order_ord_amt,
  54. tr.refund_order_ord_tfee_4 = sub.refund_order_ord_tfee,
  55. tr.refund_order_ord_num_4 = sub.refund_order_ord_num;";
  56. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  57. sql = @"
  58. UPDATE tk_report tr
  59. JOIN (
  60. SELECT
  61. accountId, DATE(RefundCreateTime) AS date,
  62. SUM(showReturnFee) AS refund_order_ord_tfee
  63. FROM tk_refund_order_details
  64. WHERE DATE(RefundCreateTime) IN @orderTimes AND accountId=@accountId
  65. GROUP BY DATE(RefundCreateTime), accountId
  66. ) AS sub
  67. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  68. SET tr.refund_order_ord_freeze_tfee = 0-sub.refund_order_ord_tfee;";
  69. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  70. sql = @"
  71. UPDATE tk_report tr
  72. JOIN (
  73. SELECT
  74. accountId, DATE(RefundFinishTime) AS date,
  75. SUM(showReturnFee) AS refund_order_ord_tfee
  76. FROM tk_refund_order_details
  77. WHERE DATE(RefundFinishTime) IN @orderTimes AND refundStatus=2 AND accountId=@accountId
  78. GROUP BY DATE(RefundFinishTime), accountId
  79. ) AS sub
  80. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  81. SET tr.refund_order_ord_deduct_tfee = 0-sub.refund_order_ord_tfee;";
  82. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  83. sql = @"
  84. UPDATE tk_report tr
  85. JOIN (
  86. SELECT
  87. accountId, DATE(RefundFinishTime) AS date,
  88. SUM(showReturnFee) AS refund_order_ord_tfee
  89. FROM tk_refund_order_details
  90. WHERE DATE(RefundFinishTime) IN @orderTimes AND refundStatus IN (2,3) AND accountId=@accountId
  91. GROUP BY DATE(RefundFinishTime), accountId
  92. ) AS sub
  93. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  94. SET tr.refund_order_ord_unfreeze_tfee = sub.refund_order_ord_tfee;";
  95. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  96. //refundStatus3 失败
  97. //2 成功
  98. //4创建
  99. //public decimal refund_order_ord_deduct_tfee { get; set; } = 0;
  100. //public decimal refund_order_ord_freeze_tfee { get; set; } = 0;
  101. //public decimal refund_order_ord_unfreeze_tfee { get; set; } = 0;
  102. return total;
  103. }
  104. public async Task<int> GetIncyRefundOrdersAsync(int sleep)
  105. {
  106. string cacheKey = $":cache:GetIncyRefundOrders:{_accountId}";
  107. DateTime endTime = DateTime.Now;
  108. DateTime startTime = endTime.AddDays(-1);
  109. DateTime last_modifiedTime = RedisHelper.Get<DateTime>(cacheKey);
  110. ////找出数据库最新的一天
  111. //var last = new DBContext.Table("tk_order_details")
  112. // .Order("modifiedTime DESC")
  113. // .Get<TkRefundOrderDetailDTO>("accountId=@accountId", new { accountId = _accountId });
  114. if (last_modifiedTime != DateTime.MinValue)
  115. {
  116. startTime = last_modifiedTime;
  117. }
  118. else
  119. {
  120. last_modifiedTime = startTime;
  121. }
  122. //当日往前查询
  123. (int total, DateTime max_modifiedTime, List<DateTime> orderTimes) = await GetTkRefundOrdersAsync(startTime, endTime, last_modifiedTime, true, sleep);
  124. if (max_modifiedTime != DateTime.MinValue)
  125. {
  126. RedisHelper.Set(cacheKey, max_modifiedTime);
  127. }
  128. if (_account.is_hide) return total;
  129. string sql = @"
  130. UPDATE tk_report tr
  131. JOIN (
  132. SELECT
  133. accountId, DATE(tbTradeCreateTime) AS date, SUM(refundFee) AS refund_order_ord_amt,
  134. COUNT(*) AS refund_order_ord_num, SUM(showReturnFee) AS refund_order_ord_tfee
  135. FROM tk_refund_order_details
  136. WHERE DATE(tbTradeCreateTime) IN @orderTimes AND refundStatus=2 AND accountId=@accountId
  137. GROUP BY DATE(tbTradeCreateTime), accountId
  138. ) AS sub
  139. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  140. SET tr.refund_order_ord_amt = sub.refund_order_ord_amt,
  141. tr.refund_order_ord_tfee = sub.refund_order_ord_tfee,
  142. tr.refund_order_ord_num = sub.refund_order_ord_num;";
  143. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  144. sql = @"
  145. UPDATE tk_report tr
  146. JOIN (
  147. SELECT
  148. accountId, DATE(tbTradeCreateTime) AS date, SUM(refundFee) AS refund_order_ord_amt,
  149. COUNT(*) AS refund_order_ord_num, SUM(showReturnFee) AS refund_order_ord_tfee
  150. FROM tk_refund_order_details
  151. WHERE DATE(tbTradeCreateTime) IN @orderTimes AND refundStatus=4 AND accountId=@accountId
  152. GROUP BY DATE(tbTradeCreateTime), accountId
  153. ) AS sub
  154. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  155. SET tr.refund_order_ord_amt_4 = sub.refund_order_ord_amt,
  156. tr.refund_order_ord_tfee_4 = sub.refund_order_ord_tfee,
  157. tr.refund_order_ord_num_4 = sub.refund_order_ord_num;";
  158. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  159. sql = @"
  160. UPDATE tk_report tr
  161. JOIN (
  162. SELECT
  163. accountId, DATE(RefundCreateTime) AS date,
  164. SUM(showReturnFee) AS refund_order_ord_tfee
  165. FROM tk_refund_order_details
  166. WHERE DATE(RefundCreateTime) IN @orderTimes AND accountId=@accountId
  167. GROUP BY DATE(RefundCreateTime), accountId
  168. ) AS sub
  169. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  170. SET tr.refund_order_ord_freeze_tfee = 0-sub.refund_order_ord_tfee;";
  171. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  172. sql = @"
  173. UPDATE tk_report tr
  174. JOIN (
  175. SELECT
  176. accountId, DATE(RefundFinishTime) AS date,
  177. SUM(showReturnFee) AS refund_order_ord_tfee
  178. FROM tk_refund_order_details
  179. WHERE DATE(RefundFinishTime) IN @orderTimes AND refundStatus=2 AND accountId=@accountId
  180. GROUP BY DATE(RefundFinishTime), accountId
  181. ) AS sub
  182. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  183. SET tr.refund_order_ord_deduct_tfee = 0-sub.refund_order_ord_tfee;";
  184. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  185. sql = @"
  186. UPDATE tk_report tr
  187. JOIN (
  188. SELECT
  189. accountId, DATE(RefundFinishTime) AS date,
  190. SUM(showReturnFee) AS refund_order_ord_tfee
  191. FROM tk_refund_order_details
  192. WHERE DATE(RefundFinishTime) IN @orderTimes AND refundStatus IN (2,3) AND accountId=@accountId
  193. GROUP BY DATE(RefundFinishTime), accountId
  194. ) AS sub
  195. ON tr.accountId = sub.accountId AND tr.report_date = sub.date
  196. SET tr.refund_order_ord_unfreeze_tfee = sub.refund_order_ord_tfee;";
  197. DBContext.Execute(sql, new { accountId = _accountId, orderTimes });
  198. return total;
  199. }
  200. public async Task<(int, DateTime, List<DateTime>)> GetTkRefundOrdersAsync(DateTime startTime, DateTime endTime, DateTime last_modifiedTime, bool desc = true, int sleep = 100)
  201. {
  202. List<DateTime> orderTimes = [];
  203. // 确保 startTime 小于 endTime
  204. if (startTime > endTime)
  205. {
  206. (startTime, endTime) = (endTime, startTime);
  207. }
  208. DateTime max_modifiedTime = last_modifiedTime;
  209. int pageNo = 1;
  210. string positionIndex = string.Empty;
  211. int pageSize = 100;
  212. bool hasNext = true;
  213. int total = 0;
  214. while (hasNext)
  215. {
  216. var ts = DateTime.Now.Convert2UnixTimestamp(true);
  217. //string jumpType = desc ? pageNo == 1 ? "0" : "1" : "-1";
  218. string jumpType = pageNo == 1 ? "0" : "1";
  219. //string queryType = "1";
  220. //1 创建时间;3结算时间 2付款时间 4更新时间
  221. //string queryType = "2";
  222. string queryType = desc ? "4" : "2";
  223. string url = $"{base_refund_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}&toPage=1&perPageSize={pageSize * 2}&jumpType={jumpType}&isFullRefund=0&memberType=&positionIndex={positionIndex.UrlEncode()}";
  224. string body = "";
  225. JsonElement data;
  226. try
  227. {
  228. for (var i = 1; i <= 5; i++)
  229. {
  230. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  231. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  232. .AddHeaders("Cookie", _cookies);
  233. #if DEBUG
  234. #else
  235. client.Proxy = _proxy;
  236. #endif
  237. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  238. var response = client.Request(url);
  239. if (response.ResponseException != null)
  240. {
  241. _ = new LoggerLibrary("api_error", "fail")
  242. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  243. .SaveAsync();
  244. throw response.ResponseException;
  245. }
  246. body = response.Body();
  247. if (body.Contains("{\"action\":\"captcha\""))
  248. {
  249. RiskControlCore.SetRiskCookie($"tb:{_accountId}", "滑块");
  250. string message = $"【GetTkRefundOrders】【{_accountId}:{_accountName}】第 {i} 次出现滑动验证码";
  251. //NotifyCore.Notify(new NifyMessage
  252. //{
  253. // message = message,
  254. // priority = NifyMessagePriority.high,
  255. // tags = ["red_circle"]
  256. //});
  257. await Task.Delay(i * 60 * 1000);
  258. continue;
  259. }
  260. if (body.Contains("\"resultCode\":500"))
  261. {
  262. string message = $"【GetTkRefundOrders】【{_accountId}:{_accountName}】第 {i} 次出现错误\n{body}";
  263. NotifyCore.Notify(new NifyMessage
  264. {
  265. message = message,
  266. priority = NifyMessagePriority.high,
  267. tags = ["red_circle"]
  268. });
  269. await Task.Delay(i * 60 * 1000);
  270. continue;
  271. }
  272. break;
  273. }
  274. var root = body.Convert2JsonElement();
  275. var success = root.Read<bool>("success");
  276. data = root.ElementRead("data");
  277. //{"code":601,"info":{"ok":false,"message":"nologin"}}
  278. if (!success && body.Contains("nologin"))
  279. {
  280. (success, string message) = RenewCookie();
  281. if (!success)
  282. {
  283. TkPoolCore.Disabled(_accountId, _accountName, $"{body}", _account.is_hide);
  284. }
  285. return (0, DateTime.MinValue, new List<DateTime>());
  286. }
  287. if (!success)
  288. {
  289. throw new APIException(body);
  290. }
  291. }
  292. catch (Exception ex)
  293. {
  294. throw new APIException(body);
  295. }
  296. using var conn = DBContext.GetOpenConnection();
  297. conn.Open();
  298. try
  299. {
  300. foreach (var order in data.ElementRead("result").EnumerateArray())
  301. {
  302. TkRefundOrderDetailDTO item = order.GetRawText().Convert2Object<TkRefundOrderDetailDTO>();
  303. // 处理每个订单数据
  304. item.accountId = _accountId;
  305. item.accountName = _company;
  306. if (item.ModifiedTime > max_modifiedTime) max_modifiedTime = item.ModifiedTime;
  307. if (last_modifiedTime != DateTime.MinValue && last_modifiedTime >= item.ModifiedTime)
  308. {
  309. return (total, max_modifiedTime, orderTimes);
  310. }
  311. //进行订单和转链匹配
  312. orderTimes.Add(item.TbTradeCreateTime.Date);
  313. switch (item.RefundStatus)
  314. {
  315. case 4:
  316. orderTimes.Add(item.RefundCreateTime.Date);
  317. break;
  318. case 2:
  319. case 3:
  320. orderTimes.Add(item.RefundFinishTime.Date);
  321. break;
  322. }
  323. if (item.ShowReturnFee == 0)
  324. {
  325. item.ShowReturnFee = Math.Round(item.PubShareFee / item.AlipayTotalPrice * item.RefundFee, 2);
  326. }
  327. int? id = conn.Replace(item);
  328. if (id != null)
  329. {
  330. item.id = (int)id;
  331. }
  332. total++;
  333. }
  334. }
  335. catch (Exception ex)
  336. {
  337. throw;
  338. }
  339. finally
  340. {
  341. conn.Dispose();
  342. }
  343. pageNo++;
  344. hasNext = data.Read<bool>("hasNext");
  345. positionIndex = data.Read<string>("positionIndex");
  346. if (sleep > 0) await Task.Delay(sleep);
  347. }
  348. return (total, max_modifiedTime, orderTimes);
  349. }
  350. }
  351. }