shish 2 mesiacov pred
rodič
commit
415d368aa7

+ 48 - 0
biz-ghs/clear/classes/OrderCgClearClass.php

@@ -392,6 +392,54 @@ class OrderCgClearClass extends BaseClass
         return $relationCount >= $expected;
     }
 
+    /**
+     * 检测结账单关系表问题,无问题返回 null
+     * @return array|null ['reason'=>string, 'relationCount'=>int, 'expected'=>int]
+     */
+    public static function detectBackfillIssue($clear, $relationCount, array $emptyAmountClearIds, array $legacyGys2KmGysClearIds)
+    {
+        $clearId = intval(is_object($clear) ? ($clear->id ?? 0) : ($clear['id'] ?? 0));
+        if ($clearId <= 0) {
+            return null;
+        }
+        $saleIds = trim(is_object($clear) ? ($clear->saleIds ?? '') : ($clear['saleIds'] ?? ''));
+        $purchaseIds = trim(is_object($clear) ? ($clear->purchaseIds ?? '') : ($clear['purchaseIds'] ?? ''));
+        if ($saleIds === '' && $purchaseIds === '') {
+            return null;
+        }
+        $expected = self::expectedRelationCountFromClear($clear);
+        $relationCount = intval($relationCount);
+        if (in_array($clearId, $legacyGys2KmGysClearIds, true)) {
+            return [
+                'reason' => 'gys2KmGys旧格式(orderId>0,cgId=0)',
+                'relationCount' => $relationCount,
+                'expected' => $expected,
+            ];
+        }
+        if (in_array($clearId, $emptyAmountClearIds, true)) {
+            return [
+                'reason' => 'amount为空或0',
+                'relationCount' => $relationCount,
+                'expected' => $expected,
+            ];
+        }
+        if ($relationCount <= 0) {
+            return [
+                'reason' => '无关系行',
+                'relationCount' => 0,
+                'expected' => $expected,
+            ];
+        }
+        if ($expected > 0 && $relationCount < $expected) {
+            return [
+                'reason' => '关系行不足',
+                'relationCount' => $relationCount,
+                'expected' => $expected,
+            ];
+        }
+        return null;
+    }
+
     /**
      * 批量查询关系表已存在的 clearId(避免逐条 SELECT)
      * @param int[] $clearIds

+ 183 - 1
console/controllers/ClearController.php

@@ -37,12 +37,18 @@ class ClearController extends Controller
     /** @var int 每处理多少条输出一次进度,0=仅每批汇总 */
     public $logEvery = 500;
 
+    /** @var int 每种 clearStyle 抽样条数(check-order-cg-clear-sample 默认 5000) */
+    public $samplePerStyle = 5000;
+
+    /** @var int 抽样检查最多打印的问题明细条数 */
+    public $showIssues = 30;
+
     /** @var string 回填进度文件后缀(内部使用) */
     private $backfillProgressKey = '';
 
     public function options($actionID)
     {
-        return array_merge(parent::options($actionID), [
+        $options = array_merge(parent::options($actionID), [
             'dryRun',
             'batchSize',
             'sleepMs',
@@ -51,6 +57,11 @@ class ClearController extends Controller
             'limit',
             'logEvery',
         ]);
+        if ($actionID === 'check-order-cg-clear-sample') {
+            $options[] = 'samplePerStyle';
+            $options[] = 'showIssues';
+        }
+        return $options;
     }
 
     //更新 ssh 2023503
@@ -80,6 +91,22 @@ class ClearController extends Controller
 
     }
 
+    /**
+     * 抽样检查 xhOrderCgClear:clearStyle 1/2/3 各抽 N 条(默认 5000),检查是否有漏补问题
+     *
+     * 用法:
+     *   php yii clear/check-order-cg-clear-sample
+     *   php yii clear/check-order-cg-clear-sample --samplePerStyle=5000
+     *   php yii clear/check-order-cg-clear-sample --dryRun=0   # 发现问题顺带漏补
+     */
+    public function actionCheckOrderCgClearSample()
+    {
+        if (!$this->isCliOptionPassed('dryRun')) {
+            $this->dryRun = 1;
+        }
+        return $this->runSampleCheckOrderCgClear();
+    }
+
     /**
      * 漏补 xhOrderCgClear:clearStyle 1(hd2Gys) + 2(gys2Hd) + 3(gys2KmGys) 统一扫描
      *
@@ -180,6 +207,151 @@ class ClearController extends Controller
         return ExitCode::OK;
     }
 
+    /**
+     * clearStyle 1/2/3 各抽样 samplePerStyle 条,检查关系表是否有漏补问题
+     */
+    private function runSampleCheckOrderCgClear()
+    {
+        ini_set('memory_limit', '512M');
+        set_time_limit(0);
+
+        $sampleSize = intval($this->samplePerStyle);
+        if ($sampleSize < 1) {
+            $this->stderr("samplePerStyle 必须大于 0\n");
+            return ExitCode::UNSPECIFIED_ERROR;
+        }
+
+        $styleLabels = [
+            intval(dict::getDict('clearStyle', 'hd2Gys')) => 'hd2Gys(1)',
+            intval(dict::getDict('clearStyle', 'gys2Hd')) => 'gys2Hd(2)',
+            intval(dict::getDict('clearStyle', 'gys2KmGys')) => 'gys2KmGys(3)',
+        ];
+
+        $this->stdout(sprintf(
+            "抽样检查 xhOrderCgClear | 各 clearStyle 抽 %d 条(id DESC) | dryRun=%d | 最多展示 %d 条问题明细\n",
+            $sampleSize,
+            (int)$this->dryRun,
+            (int)$this->showIssues
+        ));
+
+        $totalSampled = 0;
+        $totalIssues = 0;
+        $totalFixed = 0;
+        $allIssues = [];
+        $reasonStats = [];
+
+        foreach ($styleLabels as $clearStyle => $label) {
+            $list = $this->fetchClearSampleByStyle($clearStyle, $sampleSize);
+            $sampled = count($list);
+            $totalSampled += $sampled;
+
+            if ($sampled === 0) {
+                $this->stdout("{$label}:无数据\n");
+                continue;
+            }
+
+            $clearIds = array_map('intval', array_column($list, 'id'));
+            $emptyAmountClearIds = OrderCgClearClass::getClearIdsWithEmptyAmount($clearIds);
+            $legacyGys2KmGysClearIds = OrderCgClearClass::getClearIdsWithLegacyGys2KmGysRows($clearIds);
+            $relationCountMap = OrderCgClearClass::getRelationCountMap($clearIds);
+
+            $styleIssues = 0;
+            $styleFixed = 0;
+
+            foreach ($list as $clear) {
+                $currentClearId = intval($clear['id'] ?? 0);
+                $relationCount = $relationCountMap[$currentClearId] ?? 0;
+                $issue = OrderCgClearClass::detectBackfillIssue(
+                    $clear,
+                    $relationCount,
+                    $emptyAmountClearIds,
+                    $legacyGys2KmGysClearIds
+                );
+                if ($issue === null) {
+                    continue;
+                }
+
+                $styleIssues++;
+                $totalIssues++;
+                $reason = $issue['reason'];
+                $reasonStats[$reason] = ($reasonStats[$reason] ?? 0) + 1;
+
+                $allIssues[] = [
+                    'clearId' => $currentClearId,
+                    'clearStyle' => $clearStyle,
+                    'label' => $label,
+                    'reason' => $reason,
+                    'relationCount' => $issue['relationCount'],
+                    'expected' => $issue['expected'],
+                ];
+
+                if (!$this->dryRun) {
+                    $count = OrderCgClearClass::backfillFromClear($clear, true);
+                    if ($count > 0) {
+                        $styleFixed++;
+                        $totalFixed += $count;
+                    }
+                }
+            }
+
+            $this->stdout(sprintf(
+                "%s:抽样 %d 条,问题 %d 条%s\n",
+                $label,
+                $sampled,
+                $styleIssues,
+                !$this->dryRun ? ",已写入关系 {$styleFixed} 行" : ''
+            ));
+        }
+
+        if (!empty($reasonStats)) {
+            $this->stdout("问题类型汇总:\n");
+            foreach ($reasonStats as $reason => $cnt) {
+                $this->stdout("  {$reason}:{$cnt}\n");
+            }
+        }
+
+        $showLimit = max(0, intval($this->showIssues));
+        if ($showLimit > 0 && !empty($allIssues)) {
+            $this->stdout("问题明细(前 {$showLimit} 条):\n");
+            foreach (array_slice($allIssues, 0, $showLimit) as $item) {
+                $this->stdout(sprintf(
+                    "  clearId=%d %s %s 已有=%d 应有≈%d\n",
+                    $item['clearId'],
+                    $item['label'],
+                    $item['reason'],
+                    $item['relationCount'],
+                    $item['expected']
+                ));
+            }
+            if (count($allIssues) > $showLimit) {
+                $this->stdout('  ... 还有 ' . (count($allIssues) - $showLimit) . " 条未展示\n");
+            }
+        }
+
+        $this->stdout(sprintf(
+            "检查完成:共抽样 %d 条,发现问题结账单 %d 个%s\n",
+            $totalSampled,
+            $totalIssues,
+            $totalIssues === 0 ? ',未发现漏补' : ''
+        ));
+        if (!$this->dryRun && $totalFixed > 0) {
+            $this->stdout("已漏补写入关系 {$totalFixed} 行\n");
+        }
+        if ($this->dryRun && $totalIssues > 0) {
+            $this->stdout("请加 --dryRun=0 执行漏补,或运行 backfill-order-cg-clear --reset=1 全量漏补\n");
+        }
+
+        return $totalIssues > 0 ? ExitCode::UNSPECIFIED_ERROR : ExitCode::OK;
+    }
+
+    private function fetchClearSampleByStyle($clearStyle, $limit)
+    {
+        return Yii::$app->db->createCommand(
+            'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
+            . ' WHERE clearStyle = :style ORDER BY id DESC LIMIT ' . intval($limit)
+        )->bindValue(':style', intval($clearStyle))->queryAll();
+    }
+
     /**
      * @param int[] $clearStyles
      * @param string $progressKey 进度文件后缀
@@ -447,4 +619,14 @@ class ClearController extends Controller
         }
     }
 
+    private function isCliOptionPassed($name)
+    {
+        foreach ($_SERVER['argv'] ?? [] as $arg) {
+            if ($arg === '--' . $name || strpos($arg, '--' . $name . '=') === 0) {
+                return true;
+            }
+        }
+        return false;
+    }
+
 }