ClearController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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)
  70. *
  71. * 用法:
  72. * php yii clear/backfill-order-cg-clear-hd-gys --dryRun=1 --limit=100
  73. * php yii clear/backfill-order-cg-clear-hd-gys --reset=1 --batchSize=50 --sleepMs=200
  74. */
  75. public function actionBackfillOrderCgClearHdGys()
  76. {
  77. $clearStyles = [
  78. intval(dict::getDict('clearStyle', 'hd2Gys')),
  79. intval(dict::getDict('clearStyle', 'gys2Hd')),
  80. ];
  81. return $this->runBackfillOrderCgClear(
  82. $clearStyles,
  83. 'hd_gys',
  84. 'hd2Gys(1)+gys2Hd(2)',
  85. false
  86. );
  87. }
  88. /**
  89. * 回填 xhOrderCgClear:clearStyle 3(gys2KmGys) 供货商向昆明供货商结账
  90. *
  91. * 用法:
  92. * php yii clear/rebuild-order-cg-clear-index
  93. * php yii clear/backfill-order-cg-clear-km-gys --dryRun=1 --limit=100
  94. * php yii clear/backfill-order-cg-clear-km-gys --reset=1 --batchSize=50 --sleepMs=200
  95. */
  96. public function actionBackfillOrderCgClearKmGys()
  97. {
  98. $clearStyles = [
  99. intval(dict::getDict('clearStyle', 'gys2KmGys')),
  100. ];
  101. return $this->runBackfillOrderCgClear(
  102. $clearStyles,
  103. 'km_gys',
  104. 'gys2KmGys(3)',
  105. true
  106. );
  107. }
  108. /**
  109. * @deprecated 请改用 backfill-order-cg-clear-hd-gys 与 backfill-order-cg-clear-km-gys
  110. */
  111. public function actionBackfillOrderCgClear()
  112. {
  113. $this->stderr("请使用独立脚本:\n");
  114. $this->stderr(" php yii clear/backfill-order-cg-clear-hd-gys --reset=1\n");
  115. $this->stderr(" php yii clear/backfill-order-cg-clear-km-gys --reset=1\n");
  116. return ExitCode::UNSPECIFIED_ERROR;
  117. }
  118. /**
  119. * 迁移 gys2KmGys 关系行:orderId/cgId 旧格式 -> cgId 存 xhGhsCgOrder、orderId=0
  120. *
  121. * 用法:
  122. * php yii clear/migrate-gys2-km-gys-order-cg-clear --dryRun=1
  123. * php yii clear/migrate-gys2-km-gys-order-cg-clear
  124. *
  125. * 注意:若仍存在唯一索引 order_id_clear_id(clearId,orderId),请先执行 rebuild-order-cg-clear-index
  126. */
  127. public function actionMigrateGys2KmGysOrderCgClear()
  128. {
  129. set_time_limit(0);
  130. $this->stdout("迁移 gys2KmGys 关系行 | dryRun={$this->dryRun} batchSize={$this->batchSize}\n");
  131. $count = OrderCgClearClass::migrateLegacyGys2KmGysRows((bool)$this->dryRun, $this->batchSize, $this->sleepMs);
  132. $this->stdout(($this->dryRun ? '预览' : '完成') . ":处理 {$count} 行\n");
  133. return ExitCode::OK;
  134. }
  135. /**
  136. * 重建 xhOrderCgClear 唯一索引为 (clearId, cgId, orderId)
  137. *
  138. * 用法:
  139. * php yii clear/rebuild-order-cg-clear-index --dryRun=1
  140. * php yii clear/rebuild-order-cg-clear-index
  141. */
  142. public function actionRebuildOrderCgClearIndex()
  143. {
  144. set_time_limit(0);
  145. if ($this->dryRun) {
  146. $info = OrderCgClearClass::rebuildRelationUniqueIndex(true);
  147. $this->stdout(sprintf(
  148. "预览:旧索引=%s 新索引=%s 待迁移旧格式行=%d\n",
  149. !empty($info['hasLegacyIndex']) ? '有' : '无',
  150. !empty($info['hasNewIndex']) ? '有' : '无',
  151. (int)($info['legacyRows'] ?? 0)
  152. ));
  153. return ExitCode::OK;
  154. }
  155. $this->stdout("开始重建唯一索引 uk_clear_cg_order(clearId,cgId,orderId)\n");
  156. $result = OrderCgClearClass::rebuildRelationUniqueIndex(false);
  157. $this->stdout(sprintf(
  158. "完成:删旧索引=%s 建新索引=%s 迁移旧格式行=%d\n",
  159. !empty($result['droppedLegacyIndex']) ? '是' : '否',
  160. !empty($result['addedNewIndex']) ? '是' : '否',
  161. (int)($result['migratedLegacyRows'] ?? 0)
  162. ));
  163. return ExitCode::OK;
  164. }
  165. /**
  166. * @param int[] $clearStyles
  167. * @param string $progressKey 进度文件后缀
  168. * @param string $label 日志标签
  169. * @param bool $checkLegacyGys2KmGys 是否检测 gys2KmGys 旧格式行
  170. */
  171. private function runBackfillOrderCgClear(array $clearStyles, $progressKey, $label, $checkLegacyGys2KmGys)
  172. {
  173. ini_set('memory_limit', '512M');
  174. set_time_limit(0);
  175. if ($this->batchSize < 1) {
  176. $this->stderr("batchSize 必须大于 0\n");
  177. return ExitCode::UNSPECIFIED_ERROR;
  178. }
  179. if ($this->sleepMs < 0) {
  180. $this->stderr("sleepMs 不能小于 0\n");
  181. return ExitCode::UNSPECIFIED_ERROR;
  182. }
  183. $this->backfillProgressKey = $progressKey;
  184. if ($this->reset && $this->clearId <= 0) {
  185. $this->clearBackfillProgress();
  186. $this->stdout("已重置回填进度 [{$progressKey}]\n");
  187. }
  188. $cursorId = $this->clearId > 0 ? null : $this->loadBackfillProgress();
  189. $total = 0;
  190. $inserted = 0;
  191. $skipped = 0;
  192. $batchNo = 0;
  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. $batchMinId = $currentClearId;
  230. $cursorId = $currentClearId;
  231. $saleIds = trim($clear['saleIds'] ?? '');
  232. $purchaseIds = trim($clear['purchaseIds'] ?? '');
  233. if ($saleIds === '' && $purchaseIds === '') {
  234. $skipped++;
  235. continue;
  236. }
  237. $relationCount = $relationCountMap[$currentClearId] ?? 0;
  238. if (OrderCgClearClass::shouldSkipBackfill(
  239. $clear,
  240. $relationCount,
  241. $emptyAmountClearIds,
  242. $legacyGys2KmGysClearIds
  243. )) {
  244. $skipped++;
  245. continue;
  246. }
  247. if ($this->dryRun) {
  248. if ($this->logEvery > 0 && $total % $this->logEvery === 0) {
  249. $this->stdout("dryRun 已扫描 {$total} 条,当前 clearId={$currentClearId}\n");
  250. }
  251. continue;
  252. }
  253. $count = OrderCgClearClass::backfillFromClear($clear, true);
  254. if ($count > 0) {
  255. $inserted += $count;
  256. } else {
  257. $skipped++;
  258. }
  259. if ($this->logEvery > 0 && $total % $this->logEvery === 0) {
  260. $this->stdout("进度:扫描 {$total},写入关系 {$inserted} 行,跳过 {$skipped},当前 clearId={$currentClearId}\n");
  261. }
  262. }
  263. if (!$this->dryRun && $this->clearId <= 0 && $batchMinId !== null) {
  264. $this->saveBackfillProgress($batchMinId);
  265. }
  266. $this->stdout(sprintf(
  267. "第 %d 批完成:本批 %d 条,累计扫描 %d,写入关系 %d 行,跳过 %d,checkpoint id=%d\n",
  268. $batchNo,
  269. count($list),
  270. $total,
  271. $inserted,
  272. $skipped,
  273. (int)$batchMinId
  274. ));
  275. if ($this->clearId > 0 || count($list) < $fetchLimit) {
  276. break;
  277. }
  278. $this->sleepBetweenBatch();
  279. }
  280. if (!$this->dryRun && $this->clearId <= 0 && $cursorId !== null) {
  281. $this->stdout("进度已保存,下次从 id < {$cursorId} 继续\n");
  282. }
  283. $this->stdout("全部完成 [{$label}]:扫描 {$total} 条 xhClear,写入 {$inserted} 行关系,跳过 {$skipped} 条\n");
  284. return ExitCode::OK;
  285. }
  286. /**
  287. * 按主键倒序轻量拉取一批 xhClear(只查回填所需字段,LIMIT 走主键索引)
  288. */
  289. private function fetchClearBatch(array $clearStyles, $cursorId, $limit)
  290. {
  291. $clearStyles = array_values(array_unique(array_filter(array_map('intval', $clearStyles))));
  292. if (empty($clearStyles)) {
  293. return [];
  294. }
  295. $inParts = [];
  296. $params = [];
  297. foreach ($clearStyles as $idx => $style) {
  298. $key = ':s' . $idx;
  299. $inParts[] = $key;
  300. $params[$key] = $style;
  301. }
  302. $inSql = implode(',', $inParts);
  303. if ($this->clearId > 0) {
  304. $params[':id'] = intval($this->clearId);
  305. $row = Yii::$app->db->createCommand(
  306. 'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
  307. . ' WHERE id = :id AND clearStyle IN (' . $inSql . ') LIMIT 1'
  308. )->bindValues($params)->queryOne();
  309. return $row ? [$row] : [];
  310. }
  311. $sql = 'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
  312. . ' WHERE clearStyle IN (' . $inSql . ')';
  313. if ($cursorId !== null) {
  314. $sql .= ' AND id < :cursorId';
  315. $params[':cursorId'] = intval($cursorId);
  316. }
  317. $sql .= ' ORDER BY id DESC LIMIT ' . intval($limit);
  318. return Yii::$app->db->createCommand($sql)->bindValues($params)->queryAll();
  319. }
  320. private function sleepBetweenBatch()
  321. {
  322. if ($this->sleepMs > 0) {
  323. usleep($this->sleepMs * 1000);
  324. }
  325. }
  326. private function getBackfillProgressFile()
  327. {
  328. $key = $this->backfillProgressKey !== '' ? $this->backfillProgressKey : 'all';
  329. return Yii::getAlias('@console/runtime/order_cg_clear_backfill_' . $key . '.last_id');
  330. }
  331. private function loadBackfillProgress()
  332. {
  333. $file = $this->getBackfillProgressFile();
  334. if (!is_file($file)) {
  335. return null;
  336. }
  337. $id = intval(trim((string)file_get_contents($file)));
  338. return $id > 0 ? $id : null;
  339. }
  340. private function saveBackfillProgress($clearId)
  341. {
  342. if ($this->dryRun || $this->clearId > 0) {
  343. return;
  344. }
  345. $clearId = intval($clearId);
  346. if ($clearId <= 0) {
  347. return;
  348. }
  349. $file = $this->getBackfillProgressFile();
  350. $dir = dirname($file);
  351. if (!is_dir($dir)) {
  352. mkdir($dir, 0777, true);
  353. }
  354. file_put_contents($file, (string)$clearId);
  355. }
  356. private function clearBackfillProgress()
  357. {
  358. $file = $this->getBackfillProgressFile();
  359. if (is_file($file)) {
  360. unlink($file);
  361. }
  362. }
  363. }