ClearController.php 26 KB

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