ClearController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 string 回填进度文件后缀(内部使用) */
  30. private $backfillProgressKey = '';
  31. public function options($actionID)
  32. {
  33. return array_merge(parent::options($actionID), [
  34. 'dryRun',
  35. 'batchSize',
  36. 'sleepMs',
  37. 'clearId',
  38. 'reset',
  39. 'limit',
  40. 'logEvery',
  41. ]);
  42. }
  43. //更新 ssh 2023503
  44. public function actionUpdate()
  45. {
  46. ini_set('memory_limit', '2045M');
  47. set_time_limit(0);
  48. $list = OrderClearClass::getAllByCondition(['status' => 2], null, '*', null, true);
  49. if (!empty($list)) {
  50. foreach ($list as $clear) {
  51. $payTime = $clear->payTime ?? '';
  52. $saleIds = $clear->saleIds ?? '';
  53. $ids = explode(',', trim($saleIds));
  54. print_r($ids);
  55. if (!empty($ids)) {
  56. OrderClass::updateByIds($ids, ['clearTime' => $payTime]);
  57. }
  58. $purchaseIds = $clear->purchaseIds ?? '';
  59. $purchaseIds = explode(',', $purchaseIds);
  60. print_r($purchaseIds);
  61. if (!empty($purchaseIds)) {
  62. PurchaseClass::updateByIds($purchaseIds, ['clearTime' => $payTime]);
  63. }
  64. echo "-----------------\n";
  65. }
  66. }
  67. }
  68. /**
  69. * 漏补 xhOrderCgClear:clearStyle 1(hd2Gys) + 2(gys2Hd) + 3(gys2KmGys) 统一扫描
  70. *
  71. * 仅处理:无关系行 / 关系行不足 / amount 为空 / gys2KmGys 旧格式;已完整则跳过。
  72. *
  73. * 用法:
  74. * php yii clear/backfill-order-cg-clear --dryRun=1 --limit=1000
  75. * php yii clear/backfill-order-cg-clear --reset=1 --batchSize=50 --sleepMs=200
  76. * php yii clear/backfill-order-cg-clear --clearId=123
  77. */
  78. public function actionBackfillOrderCgClear()
  79. {
  80. return $this->runBackfillOrderCgClear(
  81. OrderCgClearClass::getRelationClearStyles(),
  82. 'all',
  83. 'hd2Gys(1)+gys2Hd(2)+gys2KmGys(3)',
  84. true
  85. );
  86. }
  87. /**
  88. * @deprecated 请改用 backfill-order-cg-clear(已合并 1+2+3)
  89. */
  90. public function actionBackfillOrderCgClearHdGys()
  91. {
  92. $this->stderr("已合并至: php yii clear/backfill-order-cg-clear\n");
  93. return $this->runBackfillOrderCgClear(
  94. [
  95. intval(dict::getDict('clearStyle', 'hd2Gys')),
  96. intval(dict::getDict('clearStyle', 'gys2Hd')),
  97. ],
  98. 'hd_gys',
  99. 'hd2Gys(1)+gys2Hd(2)',
  100. false
  101. );
  102. }
  103. /**
  104. * @deprecated 请改用 backfill-order-cg-clear(已合并 1+2+3)
  105. */
  106. public function actionBackfillOrderCgClearKmGys()
  107. {
  108. $this->stderr("已合并至: php yii clear/backfill-order-cg-clear\n");
  109. return $this->runBackfillOrderCgClear(
  110. [intval(dict::getDict('clearStyle', 'gys2KmGys'))],
  111. 'km_gys',
  112. 'gys2KmGys(3)',
  113. true
  114. );
  115. }
  116. /**
  117. * 迁移 gys2KmGys 关系行:orderId/cgId 旧格式 -> cgId 存 xhGhsCgOrder、orderId=0
  118. *
  119. * 用法:
  120. * php yii clear/migrate-gys2-km-gys-order-cg-clear --dryRun=1
  121. * php yii clear/migrate-gys2-km-gys-order-cg-clear
  122. *
  123. * 注意:若仍存在唯一索引 order_id_clear_id(clearId,orderId),请先执行 rebuild-order-cg-clear-index
  124. */
  125. public function actionMigrateGys2KmGysOrderCgClear()
  126. {
  127. set_time_limit(0);
  128. $this->stdout("迁移 gys2KmGys 关系行 | dryRun={$this->dryRun} batchSize={$this->batchSize}\n");
  129. $count = OrderCgClearClass::migrateLegacyGys2KmGysRows((bool)$this->dryRun, $this->batchSize, $this->sleepMs);
  130. $this->stdout(($this->dryRun ? '预览' : '完成') . ":处理 {$count} 行\n");
  131. return ExitCode::OK;
  132. }
  133. /**
  134. * 重建 xhOrderCgClear 唯一索引为 (clearId, cgId, orderId)
  135. *
  136. * 用法:
  137. * php yii clear/rebuild-order-cg-clear-index --dryRun=1
  138. * php yii clear/rebuild-order-cg-clear-index
  139. */
  140. public function actionRebuildOrderCgClearIndex()
  141. {
  142. set_time_limit(0);
  143. if ($this->dryRun) {
  144. $info = OrderCgClearClass::rebuildRelationUniqueIndex(true);
  145. $this->stdout(sprintf(
  146. "预览:旧索引=%s 新索引=%s 待迁移旧格式行=%d\n",
  147. !empty($info['hasLegacyIndex']) ? '有' : '无',
  148. !empty($info['hasNewIndex']) ? '有' : '无',
  149. (int)($info['legacyRows'] ?? 0)
  150. ));
  151. return ExitCode::OK;
  152. }
  153. $this->stdout("开始重建唯一索引 uk_clear_cg_order(clearId,cgId,orderId)\n");
  154. $result = OrderCgClearClass::rebuildRelationUniqueIndex(false);
  155. $this->stdout(sprintf(
  156. "完成:删旧索引=%s 建新索引=%s 迁移旧格式行=%d\n",
  157. !empty($result['droppedLegacyIndex']) ? '是' : '否',
  158. !empty($result['addedNewIndex']) ? '是' : '否',
  159. (int)($result['migratedLegacyRows'] ?? 0)
  160. ));
  161. return ExitCode::OK;
  162. }
  163. /**
  164. * @param int[] $clearStyles
  165. * @param string $progressKey 进度文件后缀
  166. * @param string $label 日志标签
  167. * @param bool $checkLegacyGys2KmGys 是否检测 gys2KmGys 旧格式行
  168. */
  169. private function runBackfillOrderCgClear(array $clearStyles, $progressKey, $label, $checkLegacyGys2KmGys)
  170. {
  171. ini_set('memory_limit', '512M');
  172. set_time_limit(0);
  173. if ($this->batchSize < 1) {
  174. $this->stderr("batchSize 必须大于 0\n");
  175. return ExitCode::UNSPECIFIED_ERROR;
  176. }
  177. if ($this->sleepMs < 0) {
  178. $this->stderr("sleepMs 不能小于 0\n");
  179. return ExitCode::UNSPECIFIED_ERROR;
  180. }
  181. $this->backfillProgressKey = $progressKey;
  182. if ($this->reset && $this->clearId <= 0) {
  183. $this->clearBackfillProgress();
  184. $this->stdout("已重置回填进度 [{$progressKey}]\n");
  185. }
  186. $cursorId = $this->clearId > 0 ? null : $this->loadBackfillProgress();
  187. $total = 0;
  188. $inserted = 0;
  189. $skipped = 0;
  190. $needBackfill = 0;
  191. $batchNo = 0;
  192. $styleStats = [];
  193. $this->stdout(sprintf(
  194. "开始漏补 xhOrderCgClear [%s] | id DESC 分批 | dryRun=%d batchSize=%d sleepMs=%d limit=%d | 续跑 id<%s | 进度=%s\n",
  195. $label,
  196. (int)$this->dryRun,
  197. $this->batchSize,
  198. $this->sleepMs,
  199. (int)$this->limit,
  200. $cursorId === null ? 'max' : (string)$cursorId,
  201. $this->getBackfillProgressFile()
  202. ));
  203. while (true) {
  204. if ($this->limit > 0 && $total >= $this->limit) {
  205. break;
  206. }
  207. $fetchLimit = $this->batchSize;
  208. if ($this->limit > 0) {
  209. $fetchLimit = min($fetchLimit, $this->limit - $total);
  210. if ($fetchLimit < 1) {
  211. break;
  212. }
  213. }
  214. $list = $this->fetchClearBatch($clearStyles, $cursorId, $fetchLimit);
  215. if (empty($list)) {
  216. break;
  217. }
  218. $batchNo++;
  219. $batchMinId = null;
  220. $clearIds = array_map('intval', array_column($list, 'id'));
  221. $emptyAmountClearIds = OrderCgClearClass::getClearIdsWithEmptyAmount($clearIds);
  222. $legacyGys2KmGysClearIds = $checkLegacyGys2KmGys
  223. ? OrderCgClearClass::getClearIdsWithLegacyGys2KmGysRows($clearIds)
  224. : [];
  225. $relationCountMap = OrderCgClearClass::getRelationCountMap($clearIds);
  226. foreach ($list as $clear) {
  227. $total++;
  228. $currentClearId = intval($clear['id'] ?? 0);
  229. $clearStyle = intval($clear['clearStyle'] ?? 0);
  230. $batchMinId = $currentClearId;
  231. $cursorId = $currentClearId;
  232. if (!isset($styleStats[$clearStyle])) {
  233. $styleStats[$clearStyle] = ['scan' => 0, 'need' => 0, 'skip' => 0];
  234. }
  235. $styleStats[$clearStyle]['scan']++;
  236. $saleIds = trim($clear['saleIds'] ?? '');
  237. $purchaseIds = trim($clear['purchaseIds'] ?? '');
  238. if ($saleIds === '' && $purchaseIds === '') {
  239. $skipped++;
  240. $styleStats[$clearStyle]['skip']++;
  241. continue;
  242. }
  243. $relationCount = $relationCountMap[$currentClearId] ?? 0;
  244. if (OrderCgClearClass::shouldSkipBackfill(
  245. $clear,
  246. $relationCount,
  247. $emptyAmountClearIds,
  248. $legacyGys2KmGysClearIds
  249. )) {
  250. $skipped++;
  251. $styleStats[$clearStyle]['skip']++;
  252. continue;
  253. }
  254. $needBackfill++;
  255. $styleStats[$clearStyle]['need']++;
  256. if ($this->dryRun) {
  257. $expected = OrderCgClearClass::expectedRelationCountFromClear($clear);
  258. $this->stdout(sprintf(
  259. "需漏补 clearId=%d clearStyle=%d 已有关系=%d 应有≈%d\n",
  260. $currentClearId,
  261. $clearStyle,
  262. $relationCount,
  263. $expected
  264. ));
  265. if ($this->logEvery > 0 && $needBackfill % $this->logEvery === 0) {
  266. $this->stdout("dryRun 需漏补累计 {$needBackfill} 条\n");
  267. }
  268. continue;
  269. }
  270. $count = OrderCgClearClass::backfillFromClear($clear, true);
  271. if ($count > 0) {
  272. $inserted += $count;
  273. } else {
  274. $skipped++;
  275. $styleStats[$clearStyle]['skip']++;
  276. $styleStats[$clearStyle]['need']--;
  277. $needBackfill--;
  278. }
  279. if ($this->logEvery > 0 && $total % $this->logEvery === 0) {
  280. $this->stdout("进度:扫描 {$total},需漏补 {$needBackfill},写入关系 {$inserted} 行,跳过 {$skipped},当前 clearId={$currentClearId}\n");
  281. }
  282. }
  283. if (!$this->dryRun && $this->clearId <= 0 && $batchMinId !== null) {
  284. $this->saveBackfillProgress($batchMinId);
  285. }
  286. $this->stdout(sprintf(
  287. "第 %d 批完成:本批 %d 条,累计扫描 %d,需漏补 %d,写入关系 %d 行,跳过 %d,checkpoint id=%d\n",
  288. $batchNo,
  289. count($list),
  290. $total,
  291. $needBackfill,
  292. $inserted,
  293. $skipped,
  294. (int)$batchMinId
  295. ));
  296. if ($this->clearId > 0 || count($list) < $fetchLimit) {
  297. break;
  298. }
  299. $this->sleepBetweenBatch();
  300. }
  301. if (!$this->dryRun && $this->clearId <= 0 && $cursorId !== null) {
  302. $this->stdout("进度已保存,下次从 id < {$cursorId} 继续\n");
  303. }
  304. $this->stdout(sprintf(
  305. "全部完成 [%s]:扫描 %d 条 xhClear,需漏补 %d 条,写入 %d 行关系,跳过 %d 条\n",
  306. $label,
  307. $total,
  308. $needBackfill,
  309. $inserted,
  310. $skipped
  311. ));
  312. if (!empty($styleStats)) {
  313. ksort($styleStats);
  314. foreach ($styleStats as $style => $stat) {
  315. $this->stdout(sprintf(
  316. " clearStyle=%d:扫描 %d,需漏补 %d,跳过 %d\n",
  317. $style,
  318. (int)$stat['scan'],
  319. (int)$stat['need'],
  320. (int)$stat['skip']
  321. ));
  322. }
  323. }
  324. return ExitCode::OK;
  325. }
  326. /**
  327. * 按主键倒序轻量拉取一批 xhClear(只查回填所需字段,LIMIT 走主键索引)
  328. */
  329. private function fetchClearBatch(array $clearStyles, $cursorId, $limit)
  330. {
  331. $clearStyles = array_values(array_unique(array_filter(array_map('intval', $clearStyles))));
  332. if (empty($clearStyles)) {
  333. return [];
  334. }
  335. $inParts = [];
  336. $params = [];
  337. foreach ($clearStyles as $idx => $style) {
  338. $key = ':s' . $idx;
  339. $inParts[] = $key;
  340. $params[$key] = $style;
  341. }
  342. $inSql = implode(',', $inParts);
  343. if ($this->clearId > 0) {
  344. $params[':id'] = intval($this->clearId);
  345. $row = Yii::$app->db->createCommand(
  346. 'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
  347. . ' WHERE id = :id AND clearStyle IN (' . $inSql . ') LIMIT 1'
  348. )->bindValues($params)->queryOne();
  349. return $row ? [$row] : [];
  350. }
  351. $sql = 'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
  352. . ' WHERE clearStyle IN (' . $inSql . ')';
  353. if ($cursorId !== null) {
  354. $sql .= ' AND id < :cursorId';
  355. $params[':cursorId'] = intval($cursorId);
  356. }
  357. $sql .= ' ORDER BY id DESC LIMIT ' . intval($limit);
  358. return Yii::$app->db->createCommand($sql)->bindValues($params)->queryAll();
  359. }
  360. private function sleepBetweenBatch()
  361. {
  362. if ($this->sleepMs > 0) {
  363. usleep($this->sleepMs * 1000);
  364. }
  365. }
  366. private function getBackfillProgressFile()
  367. {
  368. $key = $this->backfillProgressKey !== '' ? $this->backfillProgressKey : 'all';
  369. return Yii::getAlias('@console/runtime/order_cg_clear_backfill_' . $key . '.last_id');
  370. }
  371. private function loadBackfillProgress()
  372. {
  373. $file = $this->getBackfillProgressFile();
  374. if (!is_file($file)) {
  375. return null;
  376. }
  377. $id = intval(trim((string)file_get_contents($file)));
  378. return $id > 0 ? $id : null;
  379. }
  380. private function saveBackfillProgress($clearId)
  381. {
  382. if ($this->dryRun || $this->clearId > 0) {
  383. return;
  384. }
  385. $clearId = intval($clearId);
  386. if ($clearId <= 0) {
  387. return;
  388. }
  389. $file = $this->getBackfillProgressFile();
  390. $dir = dirname($file);
  391. if (!is_dir($dir)) {
  392. mkdir($dir, 0777, true);
  393. }
  394. file_put_contents($file, (string)$clearId);
  395. }
  396. private function clearBackfillProgress()
  397. {
  398. $file = $this->getBackfillProgressFile();
  399. if (is_file($file)) {
  400. unlink($file);
  401. }
  402. }
  403. }