ClearController.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. <?php
  2. namespace console\controllers;
  3. use bizGhs\clear\classes\OrderCgClearClass;
  4. use bizGhs\clear\models\Clear;
  5. use bizGhs\order\classes\OrderClearClass;
  6. use bizGhs\order\classes\OrderClass;
  7. use bizHd\purchase\classes\PurchaseClass;
  8. use bizHd\purchase\classes\PurchaseClearClass;
  9. use common\components\dict;
  10. use Yii;
  11. use yii\console\Controller;
  12. use yii\console\ExitCode;
  13. class ClearController extends Controller
  14. {
  15. /** @var int 是否仅预览,1=是 */
  16. public $dryRun = 0;
  17. /** @var int 每批扫描 xhClear 条数(宜小,减轻锁与内存) */
  18. public $batchSize = 50;
  19. /** @var int 每批之间休眠毫秒数,降低对线上库压力 */
  20. public $sleepMs = 100;
  21. /** @var int 指定结账单 ID,0=全部 */
  22. public $clearId = 0;
  23. /** @var int 是否重置进度从最大 id 重跑,1=是 */
  24. public $reset = 0;
  25. /** @var int 本次最多处理 xhClear 条数,0=不限制 */
  26. public $limit = 0;
  27. /** @var int 每处理多少条输出一次进度,0=仅每批汇总 */
  28. public $logEvery = 500;
  29. public function options($actionID)
  30. {
  31. return array_merge(parent::options($actionID), [
  32. 'dryRun',
  33. 'batchSize',
  34. 'sleepMs',
  35. 'clearId',
  36. 'reset',
  37. 'limit',
  38. 'logEvery',
  39. ]);
  40. }
  41. //更新 ssh 2023503
  42. public function actionUpdate()
  43. {
  44. ini_set('memory_limit', '2045M');
  45. set_time_limit(0);
  46. $list = OrderClearClass::getAllByCondition(['status' => 2], null, '*', null, true);
  47. if (!empty($list)) {
  48. foreach ($list as $clear) {
  49. $payTime = $clear->payTime ?? '';
  50. $saleIds = $clear->saleIds ?? '';
  51. $ids = explode(',', trim($saleIds));
  52. print_r($ids);
  53. if (!empty($ids)) {
  54. OrderClass::updateByIds($ids, ['clearTime' => $payTime]);
  55. }
  56. $purchaseIds = $clear->purchaseIds ?? '';
  57. $purchaseIds = explode(',', $purchaseIds);
  58. print_r($purchaseIds);
  59. if (!empty($purchaseIds)) {
  60. PurchaseClass::updateByIds($purchaseIds, ['clearTime' => $payTime]);
  61. }
  62. echo "-----------------\n";
  63. }
  64. }
  65. }
  66. /**
  67. * 历史 xhClear 回填 xhOrderCgClear
  68. *
  69. * 大数据量友好:按主键 id 分批倒序扫描,无长事务;批间休眠;关系表 clearId 批量去重。
  70. *
  71. * 用法:
  72. * php yii clear/backfill-order-cg-clear
  73. * php yii clear/backfill-order-cg-clear --batchSize=50 --sleepMs=200
  74. * php yii clear/backfill-order-cg-clear --dryRun=1 --limit=1000
  75. * php yii clear/backfill-order-cg-clear --clearId=123
  76. * php yii clear/backfill-order-cg-clear --reset=1
  77. */
  78. public function actionBackfillOrderCgClear()
  79. {
  80. ini_set('memory_limit', '512M');
  81. set_time_limit(0);
  82. if ($this->batchSize < 1) {
  83. $this->stderr("batchSize 必须大于 0\n");
  84. return ExitCode::UNSPECIFIED_ERROR;
  85. }
  86. if ($this->sleepMs < 0) {
  87. $this->stderr("sleepMs 不能小于 0\n");
  88. return ExitCode::UNSPECIFIED_ERROR;
  89. }
  90. $hd2Gys = intval(dict::getDict('clearStyle', 'hd2Gys'));
  91. $gys2Hd = intval(dict::getDict('clearStyle', 'gys2Hd'));
  92. if ($this->reset && $this->clearId <= 0) {
  93. $this->clearBackfillProgress();
  94. $this->stdout("已重置回填进度\n");
  95. }
  96. $cursorId = $this->clearId > 0 ? null : $this->loadBackfillProgress();
  97. $total = 0;
  98. $inserted = 0;
  99. $skipped = 0;
  100. $batchNo = 0;
  101. $this->stdout(sprintf(
  102. "开始回填 xhOrderCgClear | id DESC 分批 | dryRun=%d batchSize=%d sleepMs=%d limit=%d | 续跑 id<%s | 进度=%s\n",
  103. (int)$this->dryRun,
  104. $this->batchSize,
  105. $this->sleepMs,
  106. (int)$this->limit,
  107. $cursorId === null ? 'max' : (string)$cursorId,
  108. $this->getBackfillProgressFile()
  109. ));
  110. while (true) {
  111. if ($this->limit > 0 && $total >= $this->limit) {
  112. break;
  113. }
  114. $fetchLimit = $this->batchSize;
  115. if ($this->limit > 0) {
  116. $fetchLimit = min($fetchLimit, $this->limit - $total);
  117. if ($fetchLimit < 1) {
  118. break;
  119. }
  120. }
  121. $list = $this->fetchClearBatch($hd2Gys, $gys2Hd, $cursorId, $fetchLimit);
  122. if (empty($list)) {
  123. break;
  124. }
  125. $batchNo++;
  126. $batchMinId = null;
  127. $clearIds = array_map('intval', array_column($list, 'id'));
  128. $existingClearIds = OrderCgClearClass::getExistingClearIds($clearIds);
  129. $emptyAmountClearIds = OrderCgClearClass::getClearIdsWithEmptyAmount($clearIds);
  130. $existingMap = array_fill_keys($existingClearIds, true);
  131. $emptyAmountMap = array_fill_keys($emptyAmountClearIds, true);
  132. foreach ($list as $clear) {
  133. $total++;
  134. $currentClearId = intval($clear['id'] ?? 0);
  135. $batchMinId = $currentClearId;
  136. $cursorId = $currentClearId;
  137. $saleIds = trim($clear['saleIds'] ?? '');
  138. $purchaseIds = trim($clear['purchaseIds'] ?? '');
  139. if ($saleIds === '' && $purchaseIds === '') {
  140. $skipped++;
  141. continue;
  142. }
  143. if (isset($existingMap[$currentClearId]) && !isset($emptyAmountMap[$currentClearId])) {
  144. $skipped++;
  145. continue;
  146. }
  147. if ($this->dryRun) {
  148. if ($this->logEvery > 0 && $total % $this->logEvery === 0) {
  149. $this->stdout("dryRun 已扫描 {$total} 条,当前 clearId={$currentClearId}\n");
  150. }
  151. continue;
  152. }
  153. $count = OrderCgClearClass::backfillFromClear($clear, true);
  154. if ($count > 0) {
  155. $inserted += $count;
  156. } else {
  157. $skipped++;
  158. }
  159. if ($this->logEvery > 0 && $total % $this->logEvery === 0) {
  160. $this->stdout("进度:扫描 {$total},写入关系 {$inserted} 行,跳过 {$skipped},当前 clearId={$currentClearId}\n");
  161. }
  162. }
  163. if (!$this->dryRun && $this->clearId <= 0 && $batchMinId !== null) {
  164. $this->saveBackfillProgress($batchMinId);
  165. }
  166. $this->stdout(sprintf(
  167. "第 %d 批完成:本批 %d 条,累计扫描 %d,写入关系 %d 行,跳过 %d,checkpoint id=%d\n",
  168. $batchNo,
  169. count($list),
  170. $total,
  171. $inserted,
  172. $skipped,
  173. (int)$batchMinId
  174. ));
  175. if ($this->clearId > 0 || count($list) < $fetchLimit) {
  176. break;
  177. }
  178. $this->sleepBetweenBatch();
  179. }
  180. if (!$this->dryRun && $this->clearId <= 0 && $cursorId !== null) {
  181. $this->stdout("进度已保存,下次从 id < {$cursorId} 继续\n");
  182. }
  183. $this->stdout("全部完成:扫描 {$total} 条 xhClear,写入 {$inserted} 行关系,跳过 {$skipped} 条\n");
  184. return ExitCode::OK;
  185. }
  186. /**
  187. * 按主键倒序轻量拉取一批 xhClear(只查回填所需字段,LIMIT 走主键索引)
  188. */
  189. private function fetchClearBatch($hd2Gys, $gys2Hd, $cursorId, $limit)
  190. {
  191. if ($this->clearId > 0) {
  192. $row = Yii::$app->db->createCommand(
  193. 'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
  194. . ' WHERE id = :id AND clearStyle IN (:s1, :s2) LIMIT 1'
  195. )->bindValues([
  196. ':id' => intval($this->clearId),
  197. ':s1' => $hd2Gys,
  198. ':s2' => $gys2Hd,
  199. ])->queryOne();
  200. return $row ? [$row] : [];
  201. }
  202. $sql = 'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
  203. . ' WHERE clearStyle IN (:s1, :s2)';
  204. $params = [
  205. ':s1' => $hd2Gys,
  206. ':s2' => $gys2Hd,
  207. ];
  208. if ($cursorId !== null) {
  209. $sql .= ' AND id < :cursorId';
  210. $params[':cursorId'] = intval($cursorId);
  211. }
  212. $sql .= ' ORDER BY id DESC LIMIT ' . intval($limit);
  213. return Yii::$app->db->createCommand($sql)->bindValues($params)->queryAll();
  214. }
  215. private function sleepBetweenBatch()
  216. {
  217. if ($this->sleepMs > 0) {
  218. usleep($this->sleepMs * 1000);
  219. }
  220. }
  221. private function getBackfillProgressFile()
  222. {
  223. return Yii::getAlias('@console/runtime/order_cg_clear_backfill.last_id');
  224. }
  225. private function loadBackfillProgress()
  226. {
  227. $file = $this->getBackfillProgressFile();
  228. if (!is_file($file)) {
  229. return null;
  230. }
  231. $id = intval(trim((string)file_get_contents($file)));
  232. return $id > 0 ? $id : null;
  233. }
  234. private function saveBackfillProgress($clearId)
  235. {
  236. if ($this->dryRun || $this->clearId > 0) {
  237. return;
  238. }
  239. $clearId = intval($clearId);
  240. if ($clearId <= 0) {
  241. return;
  242. }
  243. $file = $this->getBackfillProgressFile();
  244. $dir = dirname($file);
  245. if (!is_dir($dir)) {
  246. mkdir($dir, 0777, true);
  247. }
  248. file_put_contents($file, (string)$clearId);
  249. }
  250. private function clearBackfillProgress()
  251. {
  252. $file = $this->getBackfillProgressFile();
  253. if (is_file($file)) {
  254. unlink($file);
  255. }
  256. }
  257. }