ClearController.php 25 KB

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