ClearController.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. /** @var int 每种 clearStyle 抽样条数(check-order-cg-clear-sample 默认 5000) */
  30. public $samplePerStyle = 5000;
  31. /** @var int 抽样检查最多打印的问题明细条数 */
  32. public $showIssues = 30;
  33. /** @var string 回填进度文件后缀(内部使用) */
  34. private $backfillProgressKey = '';
  35. public function options($actionID)
  36. {
  37. $options = array_merge(parent::options($actionID), [
  38. 'dryRun',
  39. 'batchSize',
  40. 'sleepMs',
  41. 'clearId',
  42. 'reset',
  43. 'limit',
  44. 'logEvery',
  45. ]);
  46. if ($actionID === 'check-order-cg-clear-sample') {
  47. $options[] = 'samplePerStyle';
  48. $options[] = 'showIssues';
  49. }
  50. return $options;
  51. }
  52. //更新 ssh 2023503
  53. public function actionUpdate()
  54. {
  55. ini_set('memory_limit', '2045M');
  56. set_time_limit(0);
  57. $list = OrderClearClass::getAllByCondition(['status' => 2], null, '*', null, true);
  58. if (!empty($list)) {
  59. foreach ($list as $clear) {
  60. $payTime = $clear->payTime ?? '';
  61. $saleIds = $clear->saleIds ?? '';
  62. $ids = explode(',', trim($saleIds));
  63. print_r($ids);
  64. if (!empty($ids)) {
  65. OrderClass::updateByIds($ids, ['clearTime' => $payTime]);
  66. }
  67. $purchaseIds = $clear->purchaseIds ?? '';
  68. $purchaseIds = explode(',', $purchaseIds);
  69. print_r($purchaseIds);
  70. if (!empty($purchaseIds)) {
  71. PurchaseClass::updateByIds($purchaseIds, ['clearTime' => $payTime]);
  72. }
  73. echo "-----------------\n";
  74. }
  75. }
  76. }
  77. /**
  78. * 抽样检查 xhOrderCgClear:clearStyle 1/2/3 各抽 N 条(默认 5000),检查是否有漏补问题
  79. *
  80. * 用法:
  81. * php yii clear/check-order-cg-clear-sample
  82. * php yii clear/check-order-cg-clear-sample --samplePerStyle=5000
  83. * php yii clear/check-order-cg-clear-sample --dryRun=0 # 发现问题顺带漏补
  84. */
  85. public function actionCheckOrderCgClearSample()
  86. {
  87. if (!$this->isCliOptionPassed('dryRun')) {
  88. $this->dryRun = 1;
  89. }
  90. return $this->runSampleCheckOrderCgClear();
  91. }
  92. /**
  93. * 补写 xhOrderCgClear 中 amount=0 的行(取关联订单/采购单 actPrice)
  94. *
  95. * 用法:
  96. * php yii clear/patch-order-cg-clear-amount --dryRun=1 --limit=1000
  97. * php yii clear/patch-order-cg-clear-amount --reset=1 --batchSize=100 --sleepMs=200
  98. */
  99. public function actionPatchOrderCgClearAmount()
  100. {
  101. ini_set('memory_limit', '512M');
  102. set_time_limit(0);
  103. if ($this->batchSize < 1) {
  104. $this->stderr("batchSize 必须大于 0\n");
  105. return ExitCode::UNSPECIFIED_ERROR;
  106. }
  107. $this->backfillProgressKey = 'amount';
  108. $pending = OrderCgClearClass::countZeroAmountRelationRows();
  109. if ($this->reset) {
  110. $this->clearBackfillProgress();
  111. $this->stdout("已重置补 amount 进度\n");
  112. }
  113. $cursorId = $this->loadBackfillProgress();
  114. $total = 0;
  115. $updated = 0;
  116. $skipped = 0;
  117. $batchNo = 0;
  118. $this->stdout(sprintf(
  119. "补写 amount | 待处理约 %d 行 | dryRun=%d batchSize=%d sleepMs=%d limit=%d | 续跑 id<%s | 进度=%s\n",
  120. $pending,
  121. (int)$this->dryRun,
  122. $this->batchSize,
  123. $this->sleepMs,
  124. (int)$this->limit,
  125. $cursorId === null ? 'max' : (string)$cursorId,
  126. $this->getBackfillProgressFile()
  127. ));
  128. while (true) {
  129. if ($this->limit > 0 && $total >= $this->limit) {
  130. break;
  131. }
  132. $fetchLimit = $this->batchSize;
  133. if ($this->limit > 0) {
  134. $fetchLimit = min($fetchLimit, $this->limit - $total);
  135. if ($fetchLimit < 1) {
  136. break;
  137. }
  138. }
  139. $rows = OrderCgClearClass::fetchZeroAmountRelationBatch($cursorId, $fetchLimit);
  140. if (empty($rows)) {
  141. break;
  142. }
  143. $batchNo++;
  144. $batchMinId = null;
  145. $result = OrderCgClearClass::patchZeroAmountRows($rows, (bool)$this->dryRun);
  146. $batchUpdated = intval($result['updated'] ?? 0);
  147. $batchSkipped = intval($result['skipped'] ?? 0);
  148. $updated += $batchUpdated;
  149. $skipped += $batchSkipped;
  150. $total += count($rows);
  151. foreach ($rows as $row) {
  152. $batchMinId = intval($row['id']);
  153. $cursorId = $batchMinId;
  154. }
  155. if (!$this->dryRun && $batchMinId !== null) {
  156. $this->saveBackfillProgress($batchMinId);
  157. }
  158. $this->stdout(sprintf(
  159. "第 %d 批:扫描 %d 行,补写 %d,跳过 %d,checkpoint id=%d\n",
  160. $batchNo,
  161. count($rows),
  162. $batchUpdated,
  163. $batchSkipped,
  164. (int)$batchMinId
  165. ));
  166. if (count($rows) < $fetchLimit) {
  167. break;
  168. }
  169. $this->sleepBetweenBatch();
  170. }
  171. if (!$this->dryRun && $cursorId !== null) {
  172. $this->stdout("进度已保存,下次从 id < {$cursorId} 继续\n");
  173. }
  174. $remaining = OrderCgClearClass::countZeroAmountRelationRows();
  175. $this->stdout(sprintf(
  176. "完成:处理 %d 行,补写 %d,跳过 %d,剩余 amount=0 约 %d 行\n",
  177. $total,
  178. $updated,
  179. $skipped,
  180. $remaining
  181. ));
  182. return ExitCode::OK;
  183. }
  184. /**
  185. * 漏补 xhOrderCgClear:clearStyle 1(hd2Gys) + 2(gys2Hd) + 3(gys2KmGys) 统一扫描
  186. *
  187. * 仅处理:无关系行 / 关系行不足 / amount 为空 / gys2KmGys 旧格式;已完整则跳过。
  188. *
  189. * 用法:
  190. * php yii clear/backfill-order-cg-clear --dryRun=1 --limit=1000
  191. * php yii clear/backfill-order-cg-clear --reset=1 --batchSize=50 --sleepMs=200
  192. * php yii clear/backfill-order-cg-clear --clearId=123
  193. */
  194. public function actionBackfillOrderCgClear()
  195. {
  196. return $this->runBackfillOrderCgClear(
  197. OrderCgClearClass::getRelationClearStyles(),
  198. 'all',
  199. 'hd2Gys(1)+gys2Hd(2)+gys2KmGys(3)',
  200. true
  201. );
  202. }
  203. /**
  204. * @deprecated 请改用 backfill-order-cg-clear(已合并 1+2+3)
  205. */
  206. public function actionBackfillOrderCgClearHdGys()
  207. {
  208. $this->stderr("已合并至: php yii clear/backfill-order-cg-clear\n");
  209. return $this->runBackfillOrderCgClear(
  210. [
  211. intval(dict::getDict('clearStyle', 'hd2Gys')),
  212. intval(dict::getDict('clearStyle', 'gys2Hd')),
  213. ],
  214. 'hd_gys',
  215. 'hd2Gys(1)+gys2Hd(2)',
  216. false
  217. );
  218. }
  219. /**
  220. * @deprecated 请改用 backfill-order-cg-clear(已合并 1+2+3)
  221. */
  222. public function actionBackfillOrderCgClearKmGys()
  223. {
  224. $this->stderr("已合并至: php yii clear/backfill-order-cg-clear\n");
  225. return $this->runBackfillOrderCgClear(
  226. [intval(dict::getDict('clearStyle', 'gys2KmGys'))],
  227. 'km_gys',
  228. 'gys2KmGys(3)',
  229. true
  230. );
  231. }
  232. /**
  233. * 迁移 gys2KmGys 关系行:orderId/cgId 旧格式 -> cgId 存 xhGhsCgOrder、orderId=0
  234. *
  235. * 用法:
  236. * php yii clear/migrate-gys2-km-gys-order-cg-clear --dryRun=1
  237. * php yii clear/migrate-gys2-km-gys-order-cg-clear
  238. *
  239. * 注意:若仍存在唯一索引 order_id_clear_id(clearId,orderId),请先执行 rebuild-order-cg-clear-index
  240. */
  241. public function actionMigrateGys2KmGysOrderCgClear()
  242. {
  243. set_time_limit(0);
  244. $this->stdout("迁移 gys2KmGys 关系行 | dryRun={$this->dryRun} batchSize={$this->batchSize}\n");
  245. $count = OrderCgClearClass::migrateLegacyGys2KmGysRows((bool)$this->dryRun, $this->batchSize, $this->sleepMs);
  246. $this->stdout(($this->dryRun ? '预览' : '完成') . ":处理 {$count} 行\n");
  247. return ExitCode::OK;
  248. }
  249. /**
  250. * 重建 xhOrderCgClear 唯一索引为 (clearId, cgId, orderId)
  251. *
  252. * 用法:
  253. * php yii clear/rebuild-order-cg-clear-index --dryRun=1
  254. * php yii clear/rebuild-order-cg-clear-index
  255. */
  256. public function actionRebuildOrderCgClearIndex()
  257. {
  258. set_time_limit(0);
  259. if ($this->dryRun) {
  260. $info = OrderCgClearClass::rebuildRelationUniqueIndex(true);
  261. $this->stdout(sprintf(
  262. "预览:旧索引=%s 新索引=%s 待迁移旧格式行=%d\n",
  263. !empty($info['hasLegacyIndex']) ? '有' : '无',
  264. !empty($info['hasNewIndex']) ? '有' : '无',
  265. (int)($info['legacyRows'] ?? 0)
  266. ));
  267. return ExitCode::OK;
  268. }
  269. $this->stdout("开始重建唯一索引 uk_clear_cg_order(clearId,cgId,orderId)\n");
  270. $result = OrderCgClearClass::rebuildRelationUniqueIndex(false);
  271. $this->stdout(sprintf(
  272. "完成:删旧索引=%s 建新索引=%s 迁移旧格式行=%d\n",
  273. !empty($result['droppedLegacyIndex']) ? '是' : '否',
  274. !empty($result['addedNewIndex']) ? '是' : '否',
  275. (int)($result['migratedLegacyRows'] ?? 0)
  276. ));
  277. return ExitCode::OK;
  278. }
  279. /**
  280. * clearStyle 1/2/3 各抽样 samplePerStyle 条,检查关系表是否有漏补问题
  281. */
  282. private function runSampleCheckOrderCgClear()
  283. {
  284. ini_set('memory_limit', '512M');
  285. set_time_limit(0);
  286. $sampleSize = intval($this->samplePerStyle);
  287. if ($sampleSize < 1) {
  288. $this->stderr("samplePerStyle 必须大于 0\n");
  289. return ExitCode::UNSPECIFIED_ERROR;
  290. }
  291. $styleLabels = [
  292. intval(dict::getDict('clearStyle', 'hd2Gys')) => 'hd2Gys(1)',
  293. intval(dict::getDict('clearStyle', 'gys2Hd')) => 'gys2Hd(2)',
  294. intval(dict::getDict('clearStyle', 'gys2KmGys')) => 'gys2KmGys(3)',
  295. ];
  296. $this->stdout(sprintf(
  297. "抽样检查 xhOrderCgClear | 各 clearStyle 抽 %d 条(id DESC) | dryRun=%d | 最多展示 %d 条问题明细\n",
  298. $sampleSize,
  299. (int)$this->dryRun,
  300. (int)$this->showIssues
  301. ));
  302. $totalSampled = 0;
  303. $totalIssues = 0;
  304. $totalFixed = 0;
  305. $allIssues = [];
  306. $reasonStats = [];
  307. foreach ($styleLabels as $clearStyle => $label) {
  308. $list = $this->fetchClearSampleByStyle($clearStyle, $sampleSize);
  309. $sampled = count($list);
  310. $totalSampled += $sampled;
  311. if ($sampled === 0) {
  312. $this->stdout("{$label}:无数据\n");
  313. continue;
  314. }
  315. $clearIds = array_map('intval', array_column($list, 'id'));
  316. $emptyAmountClearIds = OrderCgClearClass::getClearIdsWithEmptyAmount($clearIds);
  317. $legacyGys2KmGysClearIds = OrderCgClearClass::getClearIdsWithLegacyGys2KmGysRows($clearIds);
  318. $relationCountMap = OrderCgClearClass::getRelationCountMap($clearIds);
  319. $styleIssues = 0;
  320. $styleFixed = 0;
  321. foreach ($list as $clear) {
  322. $currentClearId = intval($clear['id'] ?? 0);
  323. $relationCount = $relationCountMap[$currentClearId] ?? 0;
  324. $issue = OrderCgClearClass::detectBackfillIssue(
  325. $clear,
  326. $relationCount,
  327. $emptyAmountClearIds,
  328. $legacyGys2KmGysClearIds
  329. );
  330. if ($issue === null) {
  331. continue;
  332. }
  333. $styleIssues++;
  334. $totalIssues++;
  335. $reason = $issue['reason'];
  336. $reasonStats[$reason] = ($reasonStats[$reason] ?? 0) + 1;
  337. $allIssues[] = [
  338. 'clearId' => $currentClearId,
  339. 'clearStyle' => $clearStyle,
  340. 'label' => $label,
  341. 'reason' => $reason,
  342. 'relationCount' => $issue['relationCount'],
  343. 'expected' => $issue['expected'],
  344. ];
  345. if (!$this->dryRun) {
  346. $count = OrderCgClearClass::backfillFromClear($clear, true);
  347. if ($count > 0) {
  348. $styleFixed++;
  349. $totalFixed += $count;
  350. }
  351. }
  352. }
  353. $this->stdout(sprintf(
  354. "%s:抽样 %d 条,问题 %d 条%s\n",
  355. $label,
  356. $sampled,
  357. $styleIssues,
  358. !$this->dryRun ? ",已写入关系 {$styleFixed} 行" : ''
  359. ));
  360. }
  361. if (!empty($reasonStats)) {
  362. $this->stdout("问题类型汇总:\n");
  363. foreach ($reasonStats as $reason => $cnt) {
  364. $this->stdout(" {$reason}:{$cnt}\n");
  365. }
  366. }
  367. $showLimit = max(0, intval($this->showIssues));
  368. if ($showLimit > 0 && !empty($allIssues)) {
  369. $this->stdout("问题明细(前 {$showLimit} 条):\n");
  370. foreach (array_slice($allIssues, 0, $showLimit) as $item) {
  371. $this->stdout(sprintf(
  372. " clearId=%d %s %s 已有=%d 应有≈%d\n",
  373. $item['clearId'],
  374. $item['label'],
  375. $item['reason'],
  376. $item['relationCount'],
  377. $item['expected']
  378. ));
  379. }
  380. if (count($allIssues) > $showLimit) {
  381. $this->stdout(' ... 还有 ' . (count($allIssues) - $showLimit) . " 条未展示\n");
  382. }
  383. }
  384. $this->stdout(sprintf(
  385. "检查完成:共抽样 %d 条,发现问题结账单 %d 个%s\n",
  386. $totalSampled,
  387. $totalIssues,
  388. $totalIssues === 0 ? ',未发现漏补' : ''
  389. ));
  390. if (!$this->dryRun && $totalFixed > 0) {
  391. $this->stdout("已漏补写入关系 {$totalFixed} 行\n");
  392. }
  393. if ($this->dryRun && $totalIssues > 0) {
  394. $this->stdout("请加 --dryRun=0 执行漏补,或运行 backfill-order-cg-clear --reset=1 全量漏补\n");
  395. }
  396. return $totalIssues > 0 ? ExitCode::UNSPECIFIED_ERROR : ExitCode::OK;
  397. }
  398. private function fetchClearSampleByStyle($clearStyle, $limit)
  399. {
  400. return Yii::$app->db->createCommand(
  401. 'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
  402. . ' WHERE clearStyle = :style ORDER BY id DESC LIMIT ' . intval($limit)
  403. )->bindValue(':style', intval($clearStyle))->queryAll();
  404. }
  405. /**
  406. * @param int[] $clearStyles
  407. * @param string $progressKey 进度文件后缀
  408. * @param string $label 日志标签
  409. * @param bool $checkLegacyGys2KmGys 是否检测 gys2KmGys 旧格式行
  410. */
  411. private function runBackfillOrderCgClear(array $clearStyles, $progressKey, $label, $checkLegacyGys2KmGys)
  412. {
  413. ini_set('memory_limit', '512M');
  414. set_time_limit(0);
  415. if ($this->batchSize < 1) {
  416. $this->stderr("batchSize 必须大于 0\n");
  417. return ExitCode::UNSPECIFIED_ERROR;
  418. }
  419. if ($this->sleepMs < 0) {
  420. $this->stderr("sleepMs 不能小于 0\n");
  421. return ExitCode::UNSPECIFIED_ERROR;
  422. }
  423. $this->backfillProgressKey = $progressKey;
  424. if ($this->reset && $this->clearId <= 0) {
  425. $this->clearBackfillProgress();
  426. $this->stdout("已重置回填进度 [{$progressKey}]\n");
  427. }
  428. $cursorId = $this->clearId > 0 ? null : $this->loadBackfillProgress();
  429. $total = 0;
  430. $inserted = 0;
  431. $skipped = 0;
  432. $needBackfill = 0;
  433. $batchNo = 0;
  434. $styleStats = [];
  435. $this->stdout(sprintf(
  436. "开始漏补 xhOrderCgClear [%s] | id DESC 分批 | dryRun=%d batchSize=%d sleepMs=%d limit=%d | 续跑 id<%s | 进度=%s\n",
  437. $label,
  438. (int)$this->dryRun,
  439. $this->batchSize,
  440. $this->sleepMs,
  441. (int)$this->limit,
  442. $cursorId === null ? 'max' : (string)$cursorId,
  443. $this->getBackfillProgressFile()
  444. ));
  445. while (true) {
  446. if ($this->limit > 0 && $total >= $this->limit) {
  447. break;
  448. }
  449. $fetchLimit = $this->batchSize;
  450. if ($this->limit > 0) {
  451. $fetchLimit = min($fetchLimit, $this->limit - $total);
  452. if ($fetchLimit < 1) {
  453. break;
  454. }
  455. }
  456. $list = $this->fetchClearBatch($clearStyles, $cursorId, $fetchLimit);
  457. if (empty($list)) {
  458. break;
  459. }
  460. $batchNo++;
  461. $batchMinId = null;
  462. $clearIds = array_map('intval', array_column($list, 'id'));
  463. $emptyAmountClearIds = OrderCgClearClass::getClearIdsWithEmptyAmount($clearIds);
  464. $legacyGys2KmGysClearIds = $checkLegacyGys2KmGys
  465. ? OrderCgClearClass::getClearIdsWithLegacyGys2KmGysRows($clearIds)
  466. : [];
  467. $relationCountMap = OrderCgClearClass::getRelationCountMap($clearIds);
  468. foreach ($list as $clear) {
  469. $total++;
  470. $currentClearId = intval($clear['id'] ?? 0);
  471. $clearStyle = intval($clear['clearStyle'] ?? 0);
  472. $batchMinId = $currentClearId;
  473. $cursorId = $currentClearId;
  474. if (!isset($styleStats[$clearStyle])) {
  475. $styleStats[$clearStyle] = ['scan' => 0, 'need' => 0, 'skip' => 0];
  476. }
  477. $styleStats[$clearStyle]['scan']++;
  478. $saleIds = trim($clear['saleIds'] ?? '');
  479. $purchaseIds = trim($clear['purchaseIds'] ?? '');
  480. if ($saleIds === '' && $purchaseIds === '') {
  481. $skipped++;
  482. $styleStats[$clearStyle]['skip']++;
  483. continue;
  484. }
  485. $relationCount = $relationCountMap[$currentClearId] ?? 0;
  486. if (OrderCgClearClass::shouldSkipBackfill(
  487. $clear,
  488. $relationCount,
  489. $emptyAmountClearIds,
  490. $legacyGys2KmGysClearIds
  491. )) {
  492. $skipped++;
  493. $styleStats[$clearStyle]['skip']++;
  494. continue;
  495. }
  496. $needBackfill++;
  497. $styleStats[$clearStyle]['need']++;
  498. if ($this->dryRun) {
  499. $expected = OrderCgClearClass::expectedRelationCountFromClear($clear);
  500. $this->stdout(sprintf(
  501. "需漏补 clearId=%d clearStyle=%d 已有关系=%d 应有≈%d\n",
  502. $currentClearId,
  503. $clearStyle,
  504. $relationCount,
  505. $expected
  506. ));
  507. if ($this->logEvery > 0 && $needBackfill % $this->logEvery === 0) {
  508. $this->stdout("dryRun 需漏补累计 {$needBackfill} 条\n");
  509. }
  510. continue;
  511. }
  512. $count = OrderCgClearClass::backfillFromClear($clear, true);
  513. if ($count > 0) {
  514. $inserted += $count;
  515. } else {
  516. $skipped++;
  517. $styleStats[$clearStyle]['skip']++;
  518. $styleStats[$clearStyle]['need']--;
  519. $needBackfill--;
  520. }
  521. if ($this->logEvery > 0 && $total % $this->logEvery === 0) {
  522. $this->stdout("进度:扫描 {$total},需漏补 {$needBackfill},写入关系 {$inserted} 行,跳过 {$skipped},当前 clearId={$currentClearId}\n");
  523. }
  524. }
  525. if (!$this->dryRun && $this->clearId <= 0 && $batchMinId !== null) {
  526. $this->saveBackfillProgress($batchMinId);
  527. }
  528. $this->stdout(sprintf(
  529. "第 %d 批完成:本批 %d 条,累计扫描 %d,需漏补 %d,写入关系 %d 行,跳过 %d,checkpoint id=%d\n",
  530. $batchNo,
  531. count($list),
  532. $total,
  533. $needBackfill,
  534. $inserted,
  535. $skipped,
  536. (int)$batchMinId
  537. ));
  538. if ($this->clearId > 0 || count($list) < $fetchLimit) {
  539. break;
  540. }
  541. $this->sleepBetweenBatch();
  542. }
  543. if (!$this->dryRun && $this->clearId <= 0 && $cursorId !== null) {
  544. $this->stdout("进度已保存,下次从 id < {$cursorId} 继续\n");
  545. }
  546. $this->stdout(sprintf(
  547. "全部完成 [%s]:扫描 %d 条 xhClear,需漏补 %d 条,写入 %d 行关系,跳过 %d 条\n",
  548. $label,
  549. $total,
  550. $needBackfill,
  551. $inserted,
  552. $skipped
  553. ));
  554. if (!empty($styleStats)) {
  555. ksort($styleStats);
  556. foreach ($styleStats as $style => $stat) {
  557. $this->stdout(sprintf(
  558. " clearStyle=%d:扫描 %d,需漏补 %d,跳过 %d\n",
  559. $style,
  560. (int)$stat['scan'],
  561. (int)$stat['need'],
  562. (int)$stat['skip']
  563. ));
  564. }
  565. }
  566. return ExitCode::OK;
  567. }
  568. /**
  569. * 按主键倒序轻量拉取一批 xhClear(只查回填所需字段,LIMIT 走主键索引)
  570. */
  571. private function fetchClearBatch(array $clearStyles, $cursorId, $limit)
  572. {
  573. $clearStyles = array_values(array_unique(array_filter(array_map('intval', $clearStyles))));
  574. if (empty($clearStyles)) {
  575. return [];
  576. }
  577. $inParts = [];
  578. $params = [];
  579. foreach ($clearStyles as $idx => $style) {
  580. $key = ':s' . $idx;
  581. $inParts[] = $key;
  582. $params[$key] = $style;
  583. }
  584. $inSql = implode(',', $inParts);
  585. if ($this->clearId > 0) {
  586. $params[':id'] = intval($this->clearId);
  587. $row = Yii::$app->db->createCommand(
  588. 'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
  589. . ' WHERE id = :id AND clearStyle IN (' . $inSql . ') LIMIT 1'
  590. )->bindValues($params)->queryOne();
  591. return $row ? [$row] : [];
  592. }
  593. $sql = 'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
  594. . ' WHERE clearStyle IN (' . $inSql . ')';
  595. if ($cursorId !== null) {
  596. $sql .= ' AND id < :cursorId';
  597. $params[':cursorId'] = intval($cursorId);
  598. }
  599. $sql .= ' ORDER BY id DESC LIMIT ' . intval($limit);
  600. return Yii::$app->db->createCommand($sql)->bindValues($params)->queryAll();
  601. }
  602. private function sleepBetweenBatch()
  603. {
  604. if ($this->sleepMs > 0) {
  605. usleep($this->sleepMs * 1000);
  606. }
  607. }
  608. private function getBackfillProgressFile()
  609. {
  610. $key = $this->backfillProgressKey !== '' ? $this->backfillProgressKey : 'all';
  611. return Yii::getAlias('@console/runtime/order_cg_clear_backfill_' . $key . '.last_id');
  612. }
  613. private function loadBackfillProgress()
  614. {
  615. $file = $this->getBackfillProgressFile();
  616. if (!is_file($file)) {
  617. return null;
  618. }
  619. $id = intval(trim((string)file_get_contents($file)));
  620. return $id > 0 ? $id : null;
  621. }
  622. private function saveBackfillProgress($clearId)
  623. {
  624. if ($this->dryRun || $this->clearId > 0) {
  625. return;
  626. }
  627. $clearId = intval($clearId);
  628. if ($clearId <= 0) {
  629. return;
  630. }
  631. $file = $this->getBackfillProgressFile();
  632. $dir = dirname($file);
  633. if (!is_dir($dir)) {
  634. mkdir($dir, 0777, true);
  635. }
  636. file_put_contents($file, (string)$clearId);
  637. }
  638. private function clearBackfillProgress()
  639. {
  640. $file = $this->getBackfillProgressFile();
  641. if (is_file($file)) {
  642. unlink($file);
  643. }
  644. }
  645. private function isCliOptionPassed($name)
  646. {
  647. foreach ($_SERVER['argv'] ?? [] as $arg) {
  648. if ($arg === '--' . $name || strpos($arg, '--' . $name . '=') === 0) {
  649. return true;
  650. }
  651. }
  652. return false;
  653. }
  654. }