Browse Source

Merge branch 'dev' of git.huaml.com:zhh/huahuibao into dev

shizhongqi 2 months ago
parent
commit
c5fe2bc71d

+ 11 - 13
biz-ghs/clear/classes/ClearClass.php

@@ -5,9 +5,9 @@ namespace bizGhs\clear\classes;
 use biz\ghs\classes\GhsClass;
 use biz\shop\classes\ShopClass;
 use bizGhs\base\classes\BaseClass;
-use bizGhs\cg\classes\CgClass;
 use bizGhs\custom\classes\CustomClass;
 use bizGhs\ghs\classes\GhsDebtRecordClass;
+use bizGhs\clear\classes\OrderCgClearClass;
 use bizGhs\order\classes\OrderClass;
 use bizGhs\order\classes\PurchaseOrderClass;
 use bizGhs\shop\classes\MainClass;
@@ -132,7 +132,6 @@ class ClearClass extends BaseClass
         $data['actPrice'] = $realPrice;
         $data['realPrice'] = $realPrice;
         $data['orderSn'] = $orderSn;
-        $data['purchaseIds'] = implode(',', $arr);
         $deadTime = time() + 120;
         $data['deadline'] = date("Y-m-d H:i:s", $deadTime);
         $data['status'] = self::STATUS_AWAIT_PAY;
@@ -158,8 +157,7 @@ class ClearClass extends BaseClass
         $order->save();
 
         $clearId = $order->id;
-        $purchaseIds = $order->purchaseIds;
-        $arr = explode(',', $purchaseIds);
+        $arr = OrderCgClearClass::getCgIdsByClearId($clearId);
         if (empty($arr)) {
             $msg = "没有找到采购订单";
             util::fail($msg);
@@ -296,9 +294,9 @@ class ClearClass extends BaseClass
     //供货商的采购信息 ssh 20210625
     public static function getGhsCgInfo($info)
     {
-        $purchaseIds = $info['purchaseIds'] ?? [];
-        $cgArr = explode(',', $purchaseIds);
-        $cgList = CgClass::getAllByCondition(['id' => ['in', $cgArr]], null, 'id,orderSn,bigNum,smallNum,realPrice,addTime', null);
+        $clearId = intval($info['id'] ?? 0);
+        $cgArr = OrderCgClearClass::getCgIdsByClearId($clearId);
+        $cgList = empty($cgArr) ? [] : PurchaseOrderClass::getAllByCondition(['id' => ['in', $cgArr]], null, 'id,orderSn,bigNum,smallNum,realPrice,addTime', null);
         $info['orderList'] = $cgList;
         $info['orderNum'] = count($cgArr);
         $clearStyle = $info['clearStyle'] ?? dict::getDict('clearStyle', 'gys2KmGys');
@@ -327,9 +325,9 @@ class ClearClass extends BaseClass
             ]);
         }
 
-        $purchaseIds = $info['purchaseIds'] ?? [];
-        $cgArr = explode(',', $purchaseIds);
-        $cgList = PurchaseClass::getAllByCondition(['id' => ['in', $cgArr]], null, '*', null);
+        $clearId = intval($info['id'] ?? 0);
+        $cgArr = OrderCgClearClass::getCgIdsByClearId($clearId);
+        $cgList = empty($cgArr) ? [] : PurchaseClass::getAllByCondition(['id' => ['in', $cgArr]], null, '*', null);
         $info['orderList'] = $cgList;
         $info['orderNum'] = count($cgArr);
         $clearStyle = $info['clearStyle'] ?? dict::getDict('clearStyle', 'hd2Gys');
@@ -344,9 +342,9 @@ class ClearClass extends BaseClass
     //完整信息 ssh 20210625
     public static function getSaleInfo($info)
     {
-        $saleIds = $info['saleIds'] ?? [];
-        $saleArr = explode(',', $saleIds);
-        $saleList = OrderClass::getAllByCondition(['id' => ['in', $saleArr]], null, '*', null);
+        $clearId = intval($info['id'] ?? 0);
+        $saleArr = OrderCgClearClass::getOrderIdsByClearId($clearId);
+        $saleList = empty($saleArr) ? [] : OrderClass::getAllByCondition(['id' => ['in', $saleArr]], null, '*', null);
         $info['orderList'] = $saleList;
         $info['orderNum'] = count($saleArr);
         $type = $info['clearStyle'] ?? dict::getDict('clearStyle', 'gys2KmGys');

+ 15 - 696
biz-ghs/clear/classes/OrderCgClearClass.php

@@ -3,13 +3,10 @@
 namespace bizGhs\clear\classes;
 
 use bizGhs\base\classes\BaseClass;
-use bizGhs\clear\models\Clear;
 use bizGhs\order\classes\OrderClass;
 use bizGhs\order\classes\PurchaseOrderClass;
 use bizHd\purchase\classes\PurchaseClass;
 use bizHd\purchase\classes\PurchaseClearClass;
-use common\components\dict;
-use Yii;
 
 class OrderCgClearClass extends BaseClass
 {
@@ -25,16 +22,16 @@ class OrderCgClearClass extends BaseClass
         if (empty($orderList)) {
             return [];
         }
-        $purchaseIds = [];
+        $hdPurchaseIds = [];
         foreach ($orderList as $order) {
             $purchaseId = is_array($order) ? ($order['purchaseId'] ?? 0) : ($order->purchaseId ?? 0);
             if (!empty($purchaseId)) {
-                $purchaseIds[] = $purchaseId;
+                $hdPurchaseIds[] = $purchaseId;
             }
         }
         $cgMap = [];
-        if (!empty($purchaseIds)) {
-            $cgList = PurchaseClass::getByIds(array_unique($purchaseIds));
+        if (!empty($hdPurchaseIds)) {
+            $cgList = PurchaseClass::getByIds(array_unique($hdPurchaseIds));
             if (!empty($cgList)) {
                 $cgMap = array_column($cgList, null, 'id');
             }
@@ -65,16 +62,16 @@ class OrderCgClearClass extends BaseClass
         if (empty($purchaseList)) {
             return [];
         }
-        $saleIds = [];
+        $ghsOrderIds = [];
         foreach ($purchaseList as $purchase) {
             $saleId = is_array($purchase) ? ($purchase['saleId'] ?? 0) : ($purchase->saleId ?? 0);
             if (!empty($saleId)) {
-                $saleIds[] = $saleId;
+                $ghsOrderIds[] = $saleId;
             }
         }
         $orderMap = [];
-        if (!empty($saleIds)) {
-            $orderList = OrderClass::getByIds(array_unique($saleIds));
+        if (!empty($ghsOrderIds)) {
+            $orderList = OrderClass::getByIds(array_unique($ghsOrderIds));
             if (!empty($orderList)) {
                 $orderMap = array_column($orderList, null, 'id');
             }
@@ -101,7 +98,7 @@ class OrderCgClearClass extends BaseClass
     }
 
     /**
-     * gys2KmGys:purchaseIds 为 xhGhsCgOrder,cgId 存基地采购单 id,orderId=0
+     * gys2KmGys:cgId 存 xhGhsCgOrder.id,orderId=0
      */
     public static function buildPairsFromGhsCgOrders($cgList)
     {
@@ -126,55 +123,6 @@ class OrderCgClearClass extends BaseClass
         return $pairs;
     }
 
-    public static function getRelationClearStyles()
-    {
-        return [
-            intval(dict::getDict('clearStyle', 'hd2Gys')),
-            intval(dict::getDict('clearStyle', 'gys2Hd')),
-            intval(dict::getDict('clearStyle', 'gys2KmGys')),
-        ];
-    }
-
-    public static function isRelationClearStyle($clearStyle)
-    {
-        return in_array(intval($clearStyle), self::getRelationClearStyles(), true);
-    }
-
-    public static function buildPairsFromClear($clear)
-    {
-        $clearStyle = intval(is_object($clear) ? ($clear->clearStyle ?? 0) : ($clear['clearStyle'] ?? 0));
-        if (!self::isRelationClearStyle($clearStyle)) {
-            return [];
-        }
-        $saleIds = is_object($clear) ? ($clear->saleIds ?? '') : ($clear['saleIds'] ?? '');
-        $purchaseIds = is_object($clear) ? ($clear->purchaseIds ?? '') : ($clear['purchaseIds'] ?? '');
-        $gys2KmGys = intval(dict::getDict('clearStyle', 'gys2KmGys'));
-        if ($clearStyle === $gys2KmGys) {
-            $cgArr = self::parseIds($purchaseIds);
-            if (empty($cgArr)) {
-                return [];
-            }
-            $cgList = PurchaseOrderClass::getAllByCondition(['id' => ['in', $cgArr]], null, '*', null, true);
-            return self::buildPairsFromGhsCgOrders($cgList);
-        }
-        $saleArr = self::parseIds($saleIds);
-        if (!empty($saleArr)) {
-            $orderList = OrderClass::getByIds($saleArr);
-            if (!empty($orderList)) {
-                return self::buildPairsFromOrders($orderList);
-            }
-        }
-        $cgArr = self::parseIds($purchaseIds);
-        if (empty($cgArr)) {
-            return [];
-        }
-        $purchaseList = PurchaseClass::getAllByCondition(['id' => ['in', $cgArr]], null, '*', null, true);
-        if (empty($purchaseList)) {
-            return [];
-        }
-        return self::buildPairsFromPurchases($purchaseList);
-    }
-
     public static function bindRelations($clear, $pairs, $status = self::STATUS_AWAIT_PAY)
     {
         $clearId = is_object($clear) ? ($clear->id ?? 0) : ($clear['id'] ?? 0);
@@ -238,32 +186,24 @@ class OrderCgClearClass extends BaseClass
         }
     }
 
-    public static function getOrderIdsByClearId($clearId, $fallbackSaleIds = '')
+    public static function getOrderIdsByClearId($clearId)
     {
         $clearId = intval($clearId);
         if ($clearId <= 0) {
-            return self::parseIds($fallbackSaleIds);
+            return [];
         }
         $list = self::getAllByCondition(['clearId' => $clearId, 'orderId>' => 0], null, 'orderId', null);
-        $ids = array_values(array_unique(array_filter(array_map('intval', array_column($list, 'orderId')))));
-        if (!empty($ids)) {
-            return $ids;
-        }
-        return self::parseIds($fallbackSaleIds);
+        return array_values(array_unique(array_filter(array_map('intval', array_column($list, 'orderId')))));
     }
 
-    public static function getCgIdsByClearId($clearId, $fallbackPurchaseIds = '')
+    public static function getCgIdsByClearId($clearId)
     {
         $clearId = intval($clearId);
         if ($clearId <= 0) {
-            return self::parseIds($fallbackPurchaseIds);
+            return [];
         }
         $list = self::getAllByCondition(['clearId' => $clearId, 'cgId>' => 0], null, 'cgId', null);
-        $ids = array_values(array_unique(array_filter(array_map('intval', array_column($list, 'cgId')))));
-        if (!empty($ids)) {
-            return $ids;
-        }
-        return self::parseIds($fallbackPurchaseIds);
+        return array_values(array_unique(array_filter(array_map('intval', array_column($list, 'cgId')))));
     }
 
     public static function getPendingClearIdByOrderId($orderId, $customId)
@@ -302,395 +242,6 @@ class OrderCgClearClass extends BaseClass
         return 0;
     }
 
-    public static function backfillFromClear($clear, $skipExistsCheck = false)
-    {
-        $clearId = is_object($clear) ? ($clear->id ?? 0) : ($clear['id'] ?? 0);
-        if (empty($clearId)) {
-            return 0;
-        }
-        if (!$skipExistsCheck) {
-            $exists = self::getByCondition(['clearId' => $clearId], true);
-            if (!empty($exists)) {
-                return 0;
-            }
-        }
-        if (!self::isRelationClearStyle(is_object($clear) ? ($clear->clearStyle ?? 0) : ($clear['clearStyle'] ?? 0))) {
-            return 0;
-        }
-        $clearStyle = intval(is_object($clear) ? ($clear->clearStyle ?? 0) : ($clear['clearStyle'] ?? 0));
-        if ($clearStyle === intval(dict::getDict('clearStyle', 'gys2KmGys'))) {
-            self::migrateLegacyGys2KmGysRowsByClearId($clearId, false);
-        }
-        $pairs = self::buildPairsFromClear($clear);
-        if (empty($pairs)) {
-            return 0;
-        }
-        $status = intval(is_object($clear) ? ($clear->status ?? 0) : ($clear['status'] ?? 0));
-        if (!in_array($status, [self::STATUS_AWAIT_PAY, self::STATUS_HAS_PAY, self::STATUS_EXPIRE], true)) {
-            $status = self::STATUS_AWAIT_PAY;
-        }
-        self::bindRelations($clear, $pairs, $status);
-        return count($pairs);
-    }
-
-    /**
-     * 从 xhClear 估算应有关系行数(saleIds 优先,否则 purchaseIds 个数)
-     */
-    public static function expectedRelationCountFromClear($clear)
-    {
-        $saleIds = is_object($clear) ? ($clear->saleIds ?? '') : ($clear['saleIds'] ?? '');
-        $purchaseIds = is_object($clear) ? ($clear->purchaseIds ?? '') : ($clear['purchaseIds'] ?? '');
-        $saleArr = self::parseIds($saleIds);
-        if (!empty($saleArr)) {
-            return count($saleArr);
-        }
-        return count(self::parseIds($purchaseIds));
-    }
-
-    /**
-     * @param int[] $clearIds
-     * @return array<int,int> clearId => 关系行数
-     */
-    public static function getRelationCountMap(array $clearIds)
-    {
-        $clearIds = array_values(array_unique(array_filter(array_map('intval', $clearIds))));
-        if (empty($clearIds)) {
-            return [];
-        }
-        $table = self::$baseFile::tableName();
-        $rows = Yii::$app->db->createCommand(
-            'SELECT clearId, COUNT(*) AS cnt FROM ' . $table
-            . ' WHERE clearId IN (' . implode(',', $clearIds) . ')'
-            . ' GROUP BY clearId'
-        )->queryAll();
-        $map = [];
-        foreach ($rows as $row) {
-            $map[intval($row['clearId'])] = intval($row['cnt']);
-        }
-        return $map;
-    }
-
-    /**
-     * 是否可跳过回填:关系行数已满、金额非空、无 gys2KmGys 旧格式
-     */
-    public static function shouldSkipBackfill($clear, $relationCount, array $emptyAmountClearIds, array $legacyGys2KmGysClearIds)
-    {
-        $clearId = intval(is_object($clear) ? ($clear->id ?? 0) : ($clear['id'] ?? 0));
-        if ($clearId <= 0) {
-            return true;
-        }
-        if (in_array($clearId, $legacyGys2KmGysClearIds, true)) {
-            return false;
-        }
-        if (in_array($clearId, $emptyAmountClearIds, true)) {
-            return false;
-        }
-        $expected = self::expectedRelationCountFromClear($clear);
-        if ($expected <= 0) {
-            return true;
-        }
-        return $relationCount >= $expected;
-    }
-
-    /**
-     * 检测结账单关系表问题,无问题返回 null
-     * @param bool $checkEmptyAmount 是否把 amount 为空/0 视为问题(抽样检查传 false)
-     * @return array|null ['reason'=>string, 'relationCount'=>int, 'expected'=>int]
-     */
-    public static function detectBackfillIssue($clear, $relationCount, array $emptyAmountClearIds, array $legacyGys2KmGysClearIds, $checkEmptyAmount = true)
-    {
-        $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 ($checkEmptyAmount && 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
-     * @return int[]
-     */
-    public static function getExistingClearIds(array $clearIds)
-    {
-        $clearIds = array_values(array_unique(array_filter(array_map('intval', $clearIds))));
-        if (empty($clearIds)) {
-            return [];
-        }
-        $list = self::getAllByCondition(['clearId' => ['in', $clearIds]], null, 'clearId', null);
-        if (empty($list)) {
-            return [];
-        }
-        return array_values(array_unique(array_map('intval', array_column($list, 'clearId'))));
-    }
-
-    /**
-     * 关系行已存在但 amount 为空/0 的 clearId(用于回填补金额)
-     * @param int[] $clearIds
-     * @return int[]
-     */
-    public static function getClearIdsWithEmptyAmount(array $clearIds)
-    {
-        $clearIds = array_values(array_unique(array_filter(array_map('intval', $clearIds))));
-        if (empty($clearIds)) {
-            return [];
-        }
-        $table = self::$baseFile::tableName();
-        $rows = Yii::$app->db->createCommand(
-            'SELECT DISTINCT clearId FROM ' . $table
-            . ' WHERE clearId IN (' . implode(',', $clearIds) . ')'
-            . ' AND (amount IS NULL OR amount = 0 OR amount = \'0\' OR amount = \'0.00\')'
-        )->queryColumn();
-        if (empty($rows)) {
-            return [];
-        }
-        return array_values(array_unique(array_map('intval', $rows)));
-    }
-
-    const LEGACY_UNIQUE_INDEX = 'order_id_clear_id';
-    const RELATION_UNIQUE_INDEX = 'uk_clear_cg_order';
-
-    /**
-     * gys2KmGys 旧数据:orderId 误存基地采购单 id、cgId=0 的 clearId
-     * @param int[] $clearIds
-     * @return int[]
-     */
-    public static function getClearIdsWithLegacyGys2KmGysRows(array $clearIds)
-    {
-        $clearIds = array_values(array_unique(array_filter(array_map('intval', $clearIds))));
-        if (empty($clearIds)) {
-            return [];
-        }
-        $gys2KmGys = intval(dict::getDict('clearStyle', 'gys2KmGys'));
-        $relTable = self::$baseFile::tableName();
-        $clearTable = Clear::tableName();
-        $rows = Yii::$app->db->createCommand(
-            'SELECT DISTINCT r.clearId FROM ' . $relTable . ' r'
-            . ' INNER JOIN ' . $clearTable . ' c ON c.id = r.clearId AND c.clearStyle = :style'
-            . ' WHERE r.clearId IN (' . implode(',', $clearIds) . ')'
-            . ' AND r.cgId = 0 AND r.orderId > 0'
-        )->bindValue(':style', $gys2KmGys)->queryColumn();
-        if (empty($rows)) {
-            return [];
-        }
-        return array_values(array_unique(array_map('intval', $rows)));
-    }
-
-    /**
-     * 将 gys2KmGys 关系行从旧格式(orderId=基地采购单id,cgId=0)迁到新格式(cgId=基地采购单id,orderId=0)
-     * 需在删除旧唯一索引 (clearId,orderId) 之后执行,或首次迁移时由 rebuildRelationUniqueIndex 串联
-     */
-    public static function migrateLegacyGys2KmGysRows($dryRun = false, $batchSize = 500, $sleepMs = 50)
-    {
-        $gys2KmGys = intval(dict::getDict('clearStyle', 'gys2KmGys'));
-        $relTable = self::$baseFile::tableName();
-        $clearTable = Clear::tableName();
-        $migrated = 0;
-        $lastId = 0;
-
-        while (true) {
-            $rows = Yii::$app->db->createCommand(
-                'SELECT r.id, r.clearId, r.orderId, r.orderSn, r.cgSn FROM ' . $relTable . ' r'
-                . ' INNER JOIN ' . $clearTable . ' c ON c.id = r.clearId AND c.clearStyle = :style'
-                . ' WHERE r.id > :lastId AND r.cgId = 0 AND r.orderId > 0'
-                . ' ORDER BY r.id ASC LIMIT ' . intval($batchSize)
-            )->bindValues([
-                ':style' => $gys2KmGys,
-                ':lastId' => $lastId,
-            ])->queryAll();
-
-            if (empty($rows)) {
-                break;
-            }
-
-            foreach ($rows as $row) {
-                $lastId = intval($row['id']);
-                $relId = $lastId;
-                $clearId = intval($row['clearId']);
-                $cgId = intval($row['orderId']);
-                $cgSn = trim($row['cgSn'] ?? '');
-                if ($cgSn === '') {
-                    $cgSn = trim($row['orderSn'] ?? '');
-                }
-
-                if (!$dryRun) {
-                    $target = self::getByCondition([
-                        'clearId' => $clearId,
-                        'orderId' => 0,
-                        'cgId' => $cgId,
-                    ], true);
-                    if (!empty($target)) {
-                        Yii::$app->db->createCommand()->delete($relTable, ['id' => $relId])->execute();
-                    } else {
-                        Yii::$app->db->createCommand()->update($relTable, [
-                            'cgId' => $cgId,
-                            'cgSn' => $cgSn,
-                            'orderId' => 0,
-                            'orderSn' => '',
-                        ], ['id' => $relId])->execute();
-                    }
-                }
-                $migrated++;
-            }
-
-            if ($sleepMs > 0 && !$dryRun) {
-                usleep($sleepMs * 1000);
-            }
-        }
-
-        return $migrated;
-    }
-
-    /**
-     * 迁移单个 gys2KmGys 结账单下的旧格式关系行
-     */
-    public static function migrateLegacyGys2KmGysRowsByClearId($clearId, $dryRun = false)
-    {
-        $clearId = intval($clearId);
-        if ($clearId <= 0) {
-            return 0;
-        }
-        $gys2KmGys = intval(dict::getDict('clearStyle', 'gys2KmGys'));
-        $clear = Clear::find()->where(['id' => $clearId, 'clearStyle' => $gys2KmGys])->one();
-        if (empty($clear)) {
-            return 0;
-        }
-        $relTable = self::$baseFile::tableName();
-        $rows = Yii::$app->db->createCommand(
-            'SELECT id, clearId, orderId, orderSn, cgSn FROM ' . $relTable
-            . ' WHERE clearId = :clearId AND cgId = 0 AND orderId > 0'
-        )->bindValue(':clearId', $clearId)->queryAll();
-        if (empty($rows)) {
-            return 0;
-        }
-        $migrated = 0;
-        foreach ($rows as $row) {
-            $relId = intval($row['id']);
-            $cgId = intval($row['orderId']);
-            $cgSn = trim($row['cgSn'] ?? '');
-            if ($cgSn === '') {
-                $cgSn = trim($row['orderSn'] ?? '');
-            }
-            if (!$dryRun) {
-                $target = self::getByCondition([
-                    'clearId' => $clearId,
-                    'orderId' => 0,
-                    'cgId' => $cgId,
-                ], true);
-                if (!empty($target)) {
-                    Yii::$app->db->createCommand()->delete($relTable, ['id' => $relId])->execute();
-                } else {
-                    Yii::$app->db->createCommand()->update($relTable, [
-                        'cgId' => $cgId,
-                        'cgSn' => $cgSn,
-                        'orderId' => 0,
-                        'orderSn' => '',
-                    ], ['id' => $relId])->execute();
-                }
-            }
-            $migrated++;
-        }
-        return $migrated;
-    }
-
-    /**
-     * 重建关系表唯一索引:(clearId,cgId,orderId)
-     * 顺序:删旧索引 -> 迁 gys2KmGys 旧行 -> 建新索引
-     */
-    public static function rebuildRelationUniqueIndex($dryRun = false)
-    {
-        $table = self::$baseFile::tableName();
-        $indexMap = self::getTableIndexMap($table);
-        $hasLegacy = isset($indexMap[self::LEGACY_UNIQUE_INDEX]);
-        $hasNew = isset($indexMap[self::RELATION_UNIQUE_INDEX]);
-        $legacyRows = intval(Yii::$app->db->createCommand(
-            'SELECT COUNT(*) FROM ' . $table . ' r'
-            . ' INNER JOIN ' . Clear::tableName() . ' c ON c.id = r.clearId AND c.clearStyle = :style'
-            . ' WHERE r.cgId = 0 AND r.orderId > 0'
-        )->bindValue(':style', intval(dict::getDict('clearStyle', 'gys2KmGys')))->queryScalar());
-
-        if ($dryRun) {
-            return [
-                'hasLegacyIndex' => $hasLegacy,
-                'hasNewIndex' => $hasNew,
-                'legacyRows' => $legacyRows,
-            ];
-        }
-
-        if ($hasLegacy) {
-            Yii::$app->db->createCommand(
-                'ALTER TABLE ' . $table . ' DROP INDEX ' . self::LEGACY_UNIQUE_INDEX
-            )->execute();
-        }
-
-        if ($legacyRows > 0) {
-            self::migrateLegacyGys2KmGysRows(false, 500, 50);
-        }
-
-        if (!$hasNew) {
-            Yii::$app->db->createCommand(
-                'ALTER TABLE ' . $table . ' ADD UNIQUE KEY ' . self::RELATION_UNIQUE_INDEX . ' (clearId, cgId, orderId)'
-            )->execute();
-        }
-
-        return [
-            'droppedLegacyIndex' => $hasLegacy,
-            'addedNewIndex' => !$hasNew,
-            'migratedLegacyRows' => $legacyRows,
-        ];
-    }
-
-    protected static function getTableIndexMap($table)
-    {
-        $rows = Yii::$app->db->createCommand('SHOW INDEX FROM ' . $table)->queryAll();
-        $map = [];
-        foreach ($rows as $row) {
-            $name = $row['Key_name'] ?? '';
-            if ($name !== '') {
-                $map[$name] = true;
-            }
-        }
-        return $map;
-    }
-
-    /**
-     * 关系行 amount 取订单/采购单 actPrice
-     */
     protected static function resolveDebtAmount($entity)
     {
         return self::normalizeAmount(self::readField($entity, 'actPrice'));
@@ -726,236 +277,4 @@ class OrderCgClearClass extends BaseClass
         return false;
     }
 
-    protected static function parseIds($idStr)
-    {
-        if ($idStr === '' || $idStr === null) {
-            return [];
-        }
-        $arr = explode(',', (string)$idStr);
-        return array_values(array_unique(array_filter(array_map('intval', $arr))));
-    }
-
-    /**
-     * xhOrderCgClear.amount 是否视为 0(含 NULL、0.00)
-     */
-    protected static function isZeroAmountSql($alias = '')
-    {
-        $prefix = $alias !== '' ? $alias . '.' : '';
-        return '(' . $prefix . 'amount IS NULL OR ' . $prefix . 'amount = 0 OR ' . $prefix . 'amount = \'0\' OR ' . $prefix . 'amount = \'0.00\')';
-    }
-
-    /**
-     * 步骤1:只从 xhOrderCgClear 查 amount=0 的行
-     * @return array[] id, clearId, orderId, cgId
-     */
-    public static function fetchZeroAmountRelationBatch($cursorId, $limit)
-    {
-        $relTable = self::$baseFile::tableName();
-        $sql = 'SELECT id, clearId, orderId, cgId FROM ' . $relTable
-            . ' WHERE ' . self::isZeroAmountSql();
-        $params = [];
-        if ($cursorId !== null) {
-            $sql .= ' AND id < :cursorId';
-            $params[':cursorId'] = intval($cursorId);
-        }
-        $sql .= ' ORDER BY id DESC LIMIT ' . intval($limit);
-        return Yii::$app->db->createCommand($sql)->bindValues($params)->queryAll();
-    }
-
-    /**
-     * 步骤2 辅助:批量取 clearStyle(仅处理步骤1命中的 clearId)
-     * @param int[] $clearIds
-     * @return array<int,int> clearId => clearStyle
-     */
-    public static function getClearStyleMap(array $clearIds)
-    {
-        $clearIds = array_values(array_unique(array_filter(array_map('intval', $clearIds))));
-        if (empty($clearIds)) {
-            return [];
-        }
-        $rows = Yii::$app->db->createCommand(
-            'SELECT id, clearStyle FROM ' . Clear::tableName()
-            . ' WHERE id IN (' . implode(',', $clearIds) . ')'
-        )->queryAll();
-        $map = [];
-        foreach ($rows as $row) {
-            $map[intval($row['id'])] = intval($row['clearStyle'] ?? 0);
-        }
-        return $map;
-    }
-
-    /**
-     * 步骤2:反查本行 amount 应写入的值(源单 actPrice)
-     */
-    public static function resolveAmountForRelationRowDirect(array $row)
-    {
-        $clearStyle = intval($row['clearStyle'] ?? 0);
-        $orderId = intval($row['orderId'] ?? 0);
-        $cgId = intval($row['cgId'] ?? 0);
-        $gys2KmGys = intval(dict::getDict('clearStyle', 'gys2KmGys'));
-        $gys2Hd = intval(dict::getDict('clearStyle', 'gys2Hd'));
-        $hd2Gys = intval(dict::getDict('clearStyle', 'hd2Gys'));
-
-        if ($clearStyle === $gys2KmGys) {
-            $ghsCgId = $cgId > 0 ? $cgId : $orderId;
-            return self::amountFromGhsCgOrderId($ghsCgId);
-        }
-        if ($clearStyle === $gys2Hd && $orderId > 0) {
-            $amount = self::amountFromGhsOrderId($orderId);
-            if ($amount !== null) {
-                return $amount;
-            }
-        }
-        if ($clearStyle === $hd2Gys && $cgId > 0) {
-            $amount = self::amountFromHdPurchaseId($cgId);
-            if ($amount !== null) {
-                return $amount;
-            }
-        }
-        if ($orderId > 0) {
-            $amount = self::amountFromGhsOrderId($orderId);
-            if ($amount !== null) {
-                return $amount;
-            }
-        }
-        if ($cgId > 0) {
-            $amount = self::amountFromHdPurchaseId($cgId);
-            if ($amount !== null) {
-                return $amount;
-            }
-            return self::amountFromGhsCgOrderId($cgId);
-        }
-        return null;
-    }
-
-    protected static function amountFromGhsOrderId($orderId)
-    {
-        $orderId = intval($orderId);
-        if ($orderId <= 0) {
-            return null;
-        }
-        $order = OrderClass::getById($orderId);
-        return self::amountFromEntity($order);
-    }
-
-    protected static function amountFromHdPurchaseId($cgId)
-    {
-        $cgId = intval($cgId);
-        if ($cgId <= 0) {
-            return null;
-        }
-        $purchase = PurchaseClass::getById($cgId);
-        return self::amountFromEntity($purchase);
-    }
-
-    protected static function amountFromGhsCgOrderId($cgId)
-    {
-        $cgId = intval($cgId);
-        if ($cgId <= 0) {
-            return null;
-        }
-        $cg = PurchaseOrderClass::getById($cgId);
-        return self::amountFromEntity($cg);
-    }
-
-    protected static function amountFromEntity($entity)
-    {
-        if (empty($entity)) {
-            return null;
-        }
-        $amount = self::resolveDebtAmount($entity);
-        if (bccomp($amount, '0', 2) <= 0) {
-            return null;
-        }
-        return $amount;
-    }
-
-    /**
-     * 步骤1~3:xhOrderCgClear amount=0 → 反查应填金额 → 按 id 更新
-     * @param array[] $rows fetchZeroAmountRelationBatch 的结果
-     * @return array{updated:int,skipped:int,details:array[]}
-     */
-    public static function patchZeroAmountRows(array $rows, $dryRun = false, $logDetails = false)
-    {
-        if (empty($rows)) {
-            return ['updated' => 0, 'skipped' => 0, 'details' => []];
-        }
-
-        $clearIds = array_values(array_unique(array_filter(array_map('intval', array_column($rows, 'clearId')))));
-        $clearStyleMap = self::getClearStyleMap($clearIds);
-
-        $table = self::$baseFile::tableName();
-        $updated = 0;
-        $skipped = 0;
-        $details = [];
-
-        foreach ($rows as $row) {
-            $relId = intval($row['id'] ?? 0);
-            $clearId = intval($row['clearId'] ?? 0);
-            if ($relId <= 0) {
-                $skipped++;
-                continue;
-            }
-
-            $row['clearStyle'] = $clearStyleMap[$clearId] ?? 0;
-            $amount = self::resolveAmountForRelationRowDirect($row);
-            if ($amount === null) {
-                $skipped++;
-                if ($logDetails) {
-                    $details[] = [
-                        'id' => $relId,
-                        'clearId' => $clearId,
-                        'orderId' => intval($row['orderId'] ?? 0),
-                        'cgId' => intval($row['cgId'] ?? 0),
-                        'status' => 'skip',
-                        'reason' => '反查不到有效 actPrice',
-                    ];
-                }
-                continue;
-            }
-
-            if (!$dryRun) {
-                $affected = Yii::$app->db->createCommand(
-                    'UPDATE ' . $table . ' SET amount = :amount WHERE id = :id AND ' . self::isZeroAmountSql()
-                )->bindValues([
-                    ':amount' => $amount,
-                    ':id' => $relId,
-                ])->execute();
-                if ($affected > 0) {
-                    $updated++;
-                    if ($logDetails) {
-                        $details[] = [
-                            'id' => $relId,
-                            'clearId' => $clearId,
-                            'amount' => $amount,
-                            'status' => 'updated',
-                        ];
-                    }
-                } else {
-                    $skipped++;
-                    if ($logDetails) {
-                        $details[] = [
-                            'id' => $relId,
-                            'status' => 'skip',
-                            'reason' => '更新时 amount 已非 0',
-                        ];
-                    }
-                }
-            } else {
-                $updated++;
-                if ($logDetails) {
-                    $details[] = [
-                        'id' => $relId,
-                        'clearId' => $clearId,
-                        'orderId' => intval($row['orderId'] ?? 0),
-                        'cgId' => intval($row['cgId'] ?? 0),
-                        'amount' => $amount,
-                        'status' => 'would_update',
-                    ];
-                }
-            }
-        }
-        return ['updated' => $updated, 'skipped' => $skipped, 'details' => $details];
-    }
-
 }

+ 2 - 15
biz-ghs/order/classes/OrderClearClass.php

@@ -120,7 +120,6 @@ class OrderClearClass extends BaseClass
 
         $modifyPrice = $post['modifyPrice'] ?? 0.00;
 
-        $purchaseArr = [];
         foreach ($list as $key => $val) {
             if ($val['sjId'] != $sjId) {
                 util::fail('只能结算自己的订单哦');
@@ -132,14 +131,6 @@ class OrderClearClass extends BaseClass
                 util::fail('每次只能结算一个客户的订单');
             }
             $amount = bcadd($amount, $val['remainDebtPrice'], 2);
-            $purchaseId = $val['purchaseId'] ?? 0;
-            if (!empty($purchaseId)) {
-                $purchaseArr[] = $purchaseId;
-            }
-        }
-        $purchaseString = '';
-        if (!empty($purchaseArr)) {
-            $purchaseString = implode(',', $purchaseArr);
         }
 
         $custom = CustomClass::getLockById($customId);
@@ -201,7 +192,6 @@ class OrderClearClass extends BaseClass
             'sjId' => $sjId,
             'shopId' => $shopId,
             'orderSn' => $orderSn,
-            'saleIds' => implode(',', $ids),
             'status' => 1,
             'clearStyle' => dict::getDict('clearStyle', 'gys2Hd'),
             'customId' => $customId,
@@ -211,7 +201,6 @@ class OrderClearClass extends BaseClass
             'customMobile' => $custom['mobile'] ?? '',
             'customAddress' => $custom['address'] ?? '',
             'deadline' => $deadline,
-            'purchaseIds' => $purchaseString,
             'payWay' => $payWay,
             'num' => count($ids),
             'ghsShopName' => $ghsShopName,
@@ -269,13 +258,11 @@ class OrderClearClass extends BaseClass
         }
         $amount = $clear->prePrice ?? 0;
 
-        $saleIds = $clear->saleIds ?? '';
-        $ids = explode(',', trim($saleIds));
+        $ids = OrderCgClearClass::getOrderIdsByClearId($clearId);
         if (empty($ids)) {
             util::fail('数据错误');
         }
-        $purchaseIds = $clear->purchaseIds ?? '';
-        $purchaseArr = explode(',', $purchaseIds);
+        $purchaseArr = OrderCgClearClass::getCgIdsByClearId($clearId);
         if (empty($purchaseArr)) {
             util::fail('数据错误');
         }

+ 8 - 14
biz-ghs/order/services/RefundOrderService.php

@@ -11,6 +11,7 @@ use biz\stat\classes\StatOutClass;
 use biz\stat\classes\StatRefundClass;
 use bizGhs\base\services\BaseService;
 use bizGhs\custom\classes\CustomClass;
+use bizGhs\clear\classes\OrderCgClearClass;
 use bizGhs\order\classes\OrderClass;
 use bizGhs\order\classes\OrderItemClass;
 use bizGhs\order\classes\RefundOrderClass;
@@ -73,27 +74,20 @@ class RefundOrderService extends BaseService
 
         $customId = $order->customId ?? 0;
         $clearList = PurchaseClearClass::getAllByCondition(['customId' => $customId, 'status' => 1], null, '*', null, true);
-        $orderIds = [];
-        $currentClearId = 0;
         if (!empty($clearList)) {
+            $now = date("Y-m-d H:i:s");
             foreach ($clearList as $clear) {
-                $saleStr = $clear->saleIds ?? '';
                 $deadline = $clear->deadline ?? '';
-                if ($deadline < date("Y-m-d H:i:s")) {
-                    $n = date("Y-m-d H:i:s");
+                if (!empty($deadline) && $deadline < $now) {
                     $clear->status = 3;
-                    $clear->remark = "账单过期,已自动取消!!参数:{$deadline} {$n}";
+                    $clear->remark = "账单过期,已自动取消!!参数:{$deadline} {$now}";
                     $clear->save();
-                } else {
-                    if (!empty($saleStr)) {
-                        $current = explode(',', $saleStr);
-                        $orderIds = array_merge($orderIds, $current);
-                        $currentClearId = $clear->id;
-                    }
+                    OrderCgClearClass::markExpireByClearId($clear->id);
                 }
             }
-            if (!empty($orderIds) && in_array($currentOrderId, $orderIds)) {
-                //有结账单要取消才能售后
+            $currentClearId = OrderCgClearClass::getPendingClearIdByOrderId($currentOrderId, $customId);
+            if ($currentClearId > 0) {
+				//有结账单要取消才能售后
                 util::success(['clearId' => $currentClearId, 'error' => 'hasUnClearOrder']);
             }
         }

+ 6 - 23
biz-hd/purchase/classes/OrderCgClearClass.php

@@ -159,32 +159,24 @@ class OrderCgClearClass extends BaseClass
         }
     }
 
-    public static function getOrderIdsByClearId($clearId, $fallbackSaleIds = '')
+    public static function getOrderIdsByClearId($clearId)
     {
         $clearId = intval($clearId);
         if ($clearId <= 0) {
-            return self::parseIds($fallbackSaleIds);
+            return [];
         }
         $list = self::getAllByCondition(['clearId' => $clearId, 'orderId>' => 0], null, 'orderId', null);
-        $ids = array_values(array_unique(array_filter(array_map('intval', array_column($list, 'orderId')))));
-        if (!empty($ids)) {
-            return $ids;
-        }
-        return self::parseIds($fallbackSaleIds);
+        return array_values(array_unique(array_filter(array_map('intval', array_column($list, 'orderId')))));
     }
 
-    public static function getCgIdsByClearId($clearId, $fallbackPurchaseIds = '')
+    public static function getCgIdsByClearId($clearId)
     {
         $clearId = intval($clearId);
         if ($clearId <= 0) {
-            return self::parseIds($fallbackPurchaseIds);
+            return [];
         }
         $list = self::getAllByCondition(['clearId' => $clearId, 'cgId>' => 0], null, 'cgId', null);
-        $ids = array_values(array_unique(array_filter(array_map('intval', array_column($list, 'cgId')))));
-        if (!empty($ids)) {
-            return $ids;
-        }
-        return self::parseIds($fallbackPurchaseIds);
+        return array_values(array_unique(array_filter(array_map('intval', array_column($list, 'cgId')))));
     }
 
     public static function getPendingClearIdByOrderId($orderId, $customId)
@@ -258,13 +250,4 @@ class OrderCgClearClass extends BaseClass
         return false;
     }
 
-    protected static function parseIds($idStr)
-    {
-        if ($idStr === '' || $idStr === null) {
-            return [];
-        }
-        $arr = explode(',', (string)$idStr);
-        return array_values(array_unique(array_filter(array_map('intval', $arr))));
-    }
-
 }

+ 7 - 12
biz-hd/purchase/classes/PurchaseClearClass.php

@@ -41,8 +41,8 @@ class PurchaseClearClass extends BaseClass
         $ghsShopName = $ghsShopName == '首店' ? '总店' : $ghsShopName;
 
         $orderSn = orderSn::getPurchaseClearSn();
-        $purchaseIds = $data['purchaseIds'];
-        $arr = explode(',', $purchaseIds);
+        $purchaseIdStr = $data['purchaseIds'] ?? '';
+        $arr = explode(',', $purchaseIdStr);
         if (empty($arr)) {
             util::fail('请选择采购单');
         }
@@ -56,7 +56,6 @@ class PurchaseClearClass extends BaseClass
         }
         $totalPrice = 0;
         $currentGhsId = $data['ghsId'] ?? 0;
-        $saleArr = [];
         foreach ($purchaseList as $purchase) {
             if ($purchase->debt != PurchaseClass::DEBT_YES) {
                 util::fail('请选择有欠款的采购单');
@@ -65,11 +64,7 @@ class PurchaseClearClass extends BaseClass
                 util::fail('请选择同个供货商的订单');
             }
             $totalPrice = bcadd($totalPrice, $purchase->remainDebtPrice, 2);
-            $saleId = $purchase->saleId;
-            $saleArr[] = $saleId;
         }
-        $saleString = implode(',', $saleArr);
-        $data['saleIds'] = $saleString;
         $data['prePrice'] = $totalPrice;
         $data['actPrice'] = $totalPrice;
         $data['realPrice'] = $totalPrice;
@@ -156,8 +151,7 @@ class PurchaseClearClass extends BaseClass
 
         $clearId = $order->id;
         $orderSn = $order->orderSn;
-        $purchaseIds = $order->purchaseIds;
-        $arr = explode(',', $purchaseIds);
+        $arr = OrderCgClearClass::getCgIdsByClearId($clearId);
 
         //供货商欠款变更
         $ghsId = $order->ghsId;
@@ -204,7 +198,7 @@ class PurchaseClearClass extends BaseClass
         }
         $clearTime = date("Y-m-d H:i:s");
         //采购单状态变更
-        $saleIds = [];
+        $saleIds = OrderCgClearClass::getOrderIdsByClearId($clearId);
         foreach ($list as $purchase) {
             $purchase->debt = PurchaseClass::DEBT_NO;
             $purchase->payWay = $payWay;
@@ -212,11 +206,12 @@ class PurchaseClearClass extends BaseClass
             $purchase->remainDebtPrice = 0;
             $purchase->clearTime = $clearTime;
             $purchase->save();
-            $saleIds[] = $purchase->saleId;
         }
 
         //销售单状态变化
-        OrderClass::updateByIds($saleIds, ['debt' => OrderClass::DEBT_NO, 'clearId' => $clearId, 'remainDebtPrice' => 0, 'clearTime' => $clearTime]);
+        if (!empty($saleIds)) {
+            OrderClass::updateByIds($saleIds, ['debt' => OrderClass::DEBT_NO, 'clearId' => $clearId, 'remainDebtPrice' => 0, 'clearTime' => $clearTime]);
+        }
 
         //客户付供货商款减少
         CustomClass::clearDebtAmountReduce($custom, $ghs, $order->actPrice, $order);

+ 0 - 764
console/controllers/ClearController.php

@@ -1,764 +0,0 @@
-<?php
-
-namespace console\controllers;
-
-use bizGhs\clear\classes\OrderCgClearClass;
-use bizGhs\clear\models\Clear;
-use bizGhs\order\classes\OrderClearClass;
-use bizGhs\order\classes\OrderClass;
-use bizHd\purchase\classes\PurchaseClass;
-use bizHd\purchase\classes\PurchaseClearClass;
-use common\components\dict;
-use Yii;
-use yii\console\Controller;
-use yii\console\ExitCode;
-
-class ClearController extends Controller
-{
-
-    /** @var int 是否仅预览,1=是 */
-    public $dryRun = 0;
-
-    /** @var int 每批扫描 xhClear 条数(宜小,减轻锁与内存) */
-    public $batchSize = 50;
-
-    /** @var int 每批之间休眠毫秒数,降低对线上库压力 */
-    public $sleepMs = 100;
-
-    /** @var int 指定结账单 ID,0=全部 */
-    public $clearId = 0;
-
-    /** @var int 是否重置进度从最大 id 重跑,1=是 */
-    public $reset = 0;
-
-    /** @var int 本次最多处理 xhClear 条数,0=不限制 */
-    public $limit = 0;
-
-    /** @var int 每处理多少条输出一次进度,0=仅每批汇总 */
-    public $logEvery = 500;
-
-    /** @var int 每种 clearStyle 抽样条数(check-order-cg-clear-sample 默认 50000) */
-    public $samplePerStyle = 50000;
-
-    /** @var int 抽样检查最多打印的问题明细条数 */
-    public $showIssues = 30;
-
-    /** @var string 回填进度文件后缀(内部使用) */
-    private $backfillProgressKey = '';
-
-    public function options($actionID)
-    {
-        $options = array_merge(parent::options($actionID), [
-            'dryRun',
-            'batchSize',
-            'sleepMs',
-            'clearId',
-            'reset',
-            'limit',
-            'logEvery',
-        ]);
-        if ($actionID === 'check-order-cg-clear-sample') {
-            $options[] = 'samplePerStyle';
-            $options[] = 'showIssues';
-        }
-        return $options;
-    }
-
-    //更新 ssh 2023503
-    public function actionUpdate()
-    {
-        ini_set('memory_limit', '2045M');
-        set_time_limit(0);
-        $list = OrderClearClass::getAllByCondition(['status' => 2], null, '*', null, true);
-        if (!empty($list)) {
-            foreach ($list as $clear) {
-                $payTime = $clear->payTime ?? '';
-                $saleIds = $clear->saleIds ?? '';
-                $ids = explode(',', trim($saleIds));
-                print_r($ids);
-                if (!empty($ids)) {
-                    OrderClass::updateByIds($ids, ['clearTime' => $payTime]);
-                }
-                $purchaseIds = $clear->purchaseIds ?? '';
-                $purchaseIds = explode(',', $purchaseIds);
-                print_r($purchaseIds);
-                if (!empty($purchaseIds)) {
-                    PurchaseClass::updateByIds($purchaseIds, ['clearTime' => $payTime]);
-                }
-                echo "-----------------\n";
-            }
-        }
-
-    }
-
-    /**
-     * 抽样检查 xhOrderCgClear:clearStyle 1/2/3 各抽 N 条(默认 50000)
-     *
-     * 检查漏补、旧格式等问题;不检 amount=0(由 patch-order-cg-clear-amount 处理)
-     *
-     * 用法:
-     *   php yii clear/check-order-cg-clear-sample
-     *   php yii clear/check-order-cg-clear-sample --samplePerStyle=50000
-     *   php yii clear/check-order-cg-clear-sample --dryRun=0   # 发现问题顺带漏补
-     */
-    public function actionCheckOrderCgClearSample()
-    {
-        if (!$this->isCliOptionPassed('dryRun')) {
-            $this->dryRun = 1;
-        }
-        return $this->runSampleCheckOrderCgClear();
-    }
-
-    /**
-     * 补写 xhOrderCgClear.amount
-     *
-     * 1. 从 xhOrderCgClear 查 amount=0
-     * 2. 按 orderId/cgId + clearStyle 反查源单 actPrice
-     * 3. 按关系行 id 更新(且仍满足 amount=0 才写,避免覆盖已有值)
-     *
-     * 用法:
-     *   php yii clear/patch-order-cg-clear-amount --dryRun=1 --limit=1000
-     *   php yii clear/patch-order-cg-clear-amount --reset=1 --batchSize=100 --sleepMs=200
-     */
-    public function actionPatchOrderCgClearAmount()
-    {
-        ini_set('memory_limit', '512M');
-        set_time_limit(0);
-
-        if ($this->batchSize < 1) {
-            $this->stderr("batchSize 必须大于 0\n");
-            return ExitCode::UNSPECIFIED_ERROR;
-        }
-
-        $this->backfillProgressKey = 'amount';
-
-        if ($this->reset) {
-            $this->clearBackfillProgress();
-            $this->stdout("已重置补 amount 进度\n");
-        }
-
-        $cursorId = $this->loadBackfillProgress();
-        $total = 0;
-        $updated = 0;
-        $skipped = 0;
-        $batchNo = 0;
-
-        $this->stdout(sprintf(
-            "补 amount | 1查xhOrderCgClear.amount=0 → 2反查actPrice → 3更新 | dryRun=%d batchSize=%d sleepMs=%d limit=%d | id<%s\n",
-            (int)$this->dryRun,
-            $this->batchSize,
-            $this->sleepMs,
-            (int)$this->limit,
-            $cursorId === null ? 'max' : (string)$cursorId
-        ));
-
-        while (true) {
-            if ($this->limit > 0 && $total >= $this->limit) {
-                break;
-            }
-            $fetchLimit = $this->batchSize;
-            if ($this->limit > 0) {
-                $fetchLimit = min($fetchLimit, $this->limit - $total);
-                if ($fetchLimit < 1) {
-                    break;
-                }
-            }
-
-            $rows = OrderCgClearClass::fetchZeroAmountRelationBatch($cursorId, $fetchLimit);
-            if (empty($rows)) {
-                break;
-            }
-            $batchNo++;
-            $batchMinId = null;
-
-            $result = OrderCgClearClass::patchZeroAmountRows($rows, (bool)$this->dryRun, (bool)$this->dryRun);
-            $batchUpdated = intval($result['updated'] ?? 0);
-            $batchSkipped = intval($result['skipped'] ?? 0);
-            if ($this->dryRun && !empty($result['details'])) {
-                foreach ($result['details'] as $detail) {
-                    if (($detail['status'] ?? '') === 'would_update') {
-                        $this->stdout(sprintf(
-                            "  预览 id=%d clearId=%d orderId=%d cgId=%d => amount=%s\n",
-                            (int)$detail['id'],
-                            (int)$detail['clearId'],
-                            (int)$detail['orderId'],
-                            (int)$detail['cgId'],
-                            $detail['amount']
-                        ));
-                    }
-                }
-            }
-            $updated += $batchUpdated;
-            $skipped += $batchSkipped;
-            $total += count($rows);
-
-            foreach ($rows as $row) {
-                $batchMinId = intval($row['id']);
-                $cursorId = $batchMinId;
-            }
-
-            if (!$this->dryRun && $batchMinId !== null) {
-                $this->saveBackfillProgress($batchMinId);
-            }
-
-            $this->stdout(sprintf(
-                "第 %d 批:amount=0 行 %d 条,补写 %d,跳过 %d,checkpoint id=%d\n",
-                $batchNo,
-                count($rows),
-                $batchUpdated,
-                $batchSkipped,
-                (int)$batchMinId
-            ));
-
-            if (count($rows) < $fetchLimit) {
-                break;
-            }
-            $this->sleepBetweenBatch();
-        }
-
-        if (!$this->dryRun && $cursorId !== null) {
-            $this->stdout("进度已保存,下次从 id < {$cursorId} 继续\n");
-        }
-        $this->stdout(sprintf(
-            "完成:处理 amount=0 行 %d 条,补写 %d,跳过 %d\n",
-            $total,
-            $updated,
-            $skipped
-        ));
-        return ExitCode::OK;
-    }
-
-    /**
-     * 漏补 xhOrderCgClear:clearStyle 1(hd2Gys) + 2(gys2Hd) + 3(gys2KmGys) 统一扫描
-     *
-     * 仅处理:无关系行 / 关系行不足 / amount 为空 / gys2KmGys 旧格式;已完整则跳过。
-     *
-     * 用法:
-     *   php yii clear/backfill-order-cg-clear --dryRun=1 --limit=1000
-     *   php yii clear/backfill-order-cg-clear --reset=1 --batchSize=50 --sleepMs=200
-     *   php yii clear/backfill-order-cg-clear --clearId=123
-     */
-    public function actionBackfillOrderCgClear()
-    {
-        return $this->runBackfillOrderCgClear(
-            OrderCgClearClass::getRelationClearStyles(),
-            'all',
-            'hd2Gys(1)+gys2Hd(2)+gys2KmGys(3)',
-            true
-        );
-    }
-
-    /**
-     * @deprecated 请改用 backfill-order-cg-clear(已合并 1+2+3)
-     */
-    public function actionBackfillOrderCgClearHdGys()
-    {
-        $this->stderr("已合并至: php yii clear/backfill-order-cg-clear\n");
-        return $this->runBackfillOrderCgClear(
-            [
-                intval(dict::getDict('clearStyle', 'hd2Gys')),
-                intval(dict::getDict('clearStyle', 'gys2Hd')),
-            ],
-            'hd_gys',
-            'hd2Gys(1)+gys2Hd(2)',
-            false
-        );
-    }
-
-    /**
-     * @deprecated 请改用 backfill-order-cg-clear(已合并 1+2+3)
-     */
-    public function actionBackfillOrderCgClearKmGys()
-    {
-        $this->stderr("已合并至: php yii clear/backfill-order-cg-clear\n");
-        return $this->runBackfillOrderCgClear(
-            [intval(dict::getDict('clearStyle', 'gys2KmGys'))],
-            'km_gys',
-            'gys2KmGys(3)',
-            true
-        );
-    }
-
-    /**
-     * 迁移 gys2KmGys 关系行:orderId/cgId 旧格式 -> cgId 存 xhGhsCgOrder、orderId=0
-     *
-     * 用法:
-     *   php yii clear/migrate-gys2-km-gys-order-cg-clear --dryRun=1
-     *   php yii clear/migrate-gys2-km-gys-order-cg-clear
-     *
-     * 注意:若仍存在唯一索引 order_id_clear_id(clearId,orderId),请先执行 rebuild-order-cg-clear-index
-     */
-    public function actionMigrateGys2KmGysOrderCgClear()
-    {
-        set_time_limit(0);
-        $this->stdout("迁移 gys2KmGys 关系行 | dryRun={$this->dryRun} batchSize={$this->batchSize}\n");
-        $count = OrderCgClearClass::migrateLegacyGys2KmGysRows((bool)$this->dryRun, $this->batchSize, $this->sleepMs);
-        $this->stdout(($this->dryRun ? '预览' : '完成') . ":处理 {$count} 行\n");
-        return ExitCode::OK;
-    }
-
-    /**
-     * 重建 xhOrderCgClear 唯一索引为 (clearId, cgId, orderId)
-     *
-     * 用法:
-     *   php yii clear/rebuild-order-cg-clear-index --dryRun=1
-     *   php yii clear/rebuild-order-cg-clear-index
-     */
-    public function actionRebuildOrderCgClearIndex()
-    {
-        set_time_limit(0);
-        if ($this->dryRun) {
-            $info = OrderCgClearClass::rebuildRelationUniqueIndex(true);
-            $this->stdout(sprintf(
-                "预览:旧索引=%s 新索引=%s 待迁移旧格式行=%d\n",
-                !empty($info['hasLegacyIndex']) ? '有' : '无',
-                !empty($info['hasNewIndex']) ? '有' : '无',
-                (int)($info['legacyRows'] ?? 0)
-            ));
-            return ExitCode::OK;
-        }
-        $this->stdout("开始重建唯一索引 uk_clear_cg_order(clearId,cgId,orderId)\n");
-        $result = OrderCgClearClass::rebuildRelationUniqueIndex(false);
-        $this->stdout(sprintf(
-            "完成:删旧索引=%s 建新索引=%s 迁移旧格式行=%d\n",
-            !empty($result['droppedLegacyIndex']) ? '是' : '否',
-            !empty($result['addedNewIndex']) ? '是' : '否',
-            (int)($result['migratedLegacyRows'] ?? 0)
-        ));
-        return ExitCode::OK;
-    }
-
-    /**
-     * clearStyle 1/2/3 各抽样 samplePerStyle 条,检查关系表漏补等问题(不含 amount=0)
-     */
-    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) | 不检 amount=0 | 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'));
-            $relationCountMap = [];
-            $legacyGys2KmGysClearIds = [];
-            foreach (array_chunk($clearIds, 2000) as $clearIdChunk) {
-                $relationCountMap += OrderCgClearClass::getRelationCountMap($clearIdChunk);
-                $legacyGys2KmGysClearIds = array_merge(
-                    $legacyGys2KmGysClearIds,
-                    OrderCgClearClass::getClearIdsWithLegacyGys2KmGysRows($clearIdChunk)
-                );
-            }
-            $legacyGys2KmGysClearIds = array_values(array_unique(array_map('intval', $legacyGys2KmGysClearIds)));
-
-            $styleIssues = 0;
-            $styleFixed = 0;
-
-            foreach ($list as $clear) {
-                $currentClearId = intval($clear['id'] ?? 0);
-                $relationCount = $relationCountMap[$currentClearId] ?? 0;
-                $issue = OrderCgClearClass::detectBackfillIssue(
-                    $clear,
-                    $relationCount,
-                    [],
-                    $legacyGys2KmGysClearIds,
-                    false
-                );
-                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");
-        }
-        if ($totalIssues === 0) {
-            $this->stdout("amount=0 请单独跑: php yii clear/patch-order-cg-clear-amount\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 进度文件后缀
-     * @param string $label 日志标签
-     * @param bool $checkLegacyGys2KmGys 是否检测 gys2KmGys 旧格式行
-     */
-    private function runBackfillOrderCgClear(array $clearStyles, $progressKey, $label, $checkLegacyGys2KmGys)
-    {
-        ini_set('memory_limit', '512M');
-        set_time_limit(0);
-
-        if ($this->batchSize < 1) {
-            $this->stderr("batchSize 必须大于 0\n");
-            return ExitCode::UNSPECIFIED_ERROR;
-        }
-        if ($this->sleepMs < 0) {
-            $this->stderr("sleepMs 不能小于 0\n");
-            return ExitCode::UNSPECIFIED_ERROR;
-        }
-
-        $this->backfillProgressKey = $progressKey;
-
-        if ($this->reset && $this->clearId <= 0) {
-            $this->clearBackfillProgress();
-            $this->stdout("已重置回填进度 [{$progressKey}]\n");
-        }
-
-        $cursorId = $this->clearId > 0 ? null : $this->loadBackfillProgress();
-        $total = 0;
-        $inserted = 0;
-        $skipped = 0;
-        $needBackfill = 0;
-        $batchNo = 0;
-        $styleStats = [];
-
-        $this->stdout(sprintf(
-            "开始漏补 xhOrderCgClear [%s] | id DESC 分批 | dryRun=%d batchSize=%d sleepMs=%d limit=%d | 续跑 id<%s | 进度=%s\n",
-            $label,
-            (int)$this->dryRun,
-            $this->batchSize,
-            $this->sleepMs,
-            (int)$this->limit,
-            $cursorId === null ? 'max' : (string)$cursorId,
-            $this->getBackfillProgressFile()
-        ));
-
-        while (true) {
-            if ($this->limit > 0 && $total >= $this->limit) {
-                break;
-            }
-            $fetchLimit = $this->batchSize;
-            if ($this->limit > 0) {
-                $fetchLimit = min($fetchLimit, $this->limit - $total);
-                if ($fetchLimit < 1) {
-                    break;
-                }
-            }
-
-            $list = $this->fetchClearBatch($clearStyles, $cursorId, $fetchLimit);
-            if (empty($list)) {
-                break;
-            }
-            $batchNo++;
-            $batchMinId = null;
-            $clearIds = array_map('intval', array_column($list, 'id'));
-            $emptyAmountClearIds = OrderCgClearClass::getClearIdsWithEmptyAmount($clearIds);
-            $legacyGys2KmGysClearIds = $checkLegacyGys2KmGys
-                ? OrderCgClearClass::getClearIdsWithLegacyGys2KmGysRows($clearIds)
-                : [];
-            $relationCountMap = OrderCgClearClass::getRelationCountMap($clearIds);
-
-            foreach ($list as $clear) {
-                $total++;
-                $currentClearId = intval($clear['id'] ?? 0);
-                $clearStyle = intval($clear['clearStyle'] ?? 0);
-                $batchMinId = $currentClearId;
-                $cursorId = $currentClearId;
-
-                if (!isset($styleStats[$clearStyle])) {
-                    $styleStats[$clearStyle] = ['scan' => 0, 'need' => 0, 'skip' => 0];
-                }
-                $styleStats[$clearStyle]['scan']++;
-
-                $saleIds = trim($clear['saleIds'] ?? '');
-                $purchaseIds = trim($clear['purchaseIds'] ?? '');
-                if ($saleIds === '' && $purchaseIds === '') {
-                    $skipped++;
-                    $styleStats[$clearStyle]['skip']++;
-                    continue;
-                }
-
-                $relationCount = $relationCountMap[$currentClearId] ?? 0;
-                if (OrderCgClearClass::shouldSkipBackfill(
-                    $clear,
-                    $relationCount,
-                    $emptyAmountClearIds,
-                    $legacyGys2KmGysClearIds
-                )) {
-                    $skipped++;
-                    $styleStats[$clearStyle]['skip']++;
-                    continue;
-                }
-
-                $needBackfill++;
-                $styleStats[$clearStyle]['need']++;
-
-                if ($this->dryRun) {
-                    $expected = OrderCgClearClass::expectedRelationCountFromClear($clear);
-                    $this->stdout(sprintf(
-                        "需漏补 clearId=%d clearStyle=%d 已有关系=%d 应有≈%d\n",
-                        $currentClearId,
-                        $clearStyle,
-                        $relationCount,
-                        $expected
-                    ));
-                    if ($this->logEvery > 0 && $needBackfill % $this->logEvery === 0) {
-                        $this->stdout("dryRun 需漏补累计 {$needBackfill} 条\n");
-                    }
-                    continue;
-                }
-
-                $count = OrderCgClearClass::backfillFromClear($clear, true);
-                if ($count > 0) {
-                    $inserted += $count;
-                } else {
-                    $skipped++;
-                    $styleStats[$clearStyle]['skip']++;
-                    $styleStats[$clearStyle]['need']--;
-                    $needBackfill--;
-                }
-                if ($this->logEvery > 0 && $total % $this->logEvery === 0) {
-                    $this->stdout("进度:扫描 {$total},需漏补 {$needBackfill},写入关系 {$inserted} 行,跳过 {$skipped},当前 clearId={$currentClearId}\n");
-                }
-            }
-
-            if (!$this->dryRun && $this->clearId <= 0 && $batchMinId !== null) {
-                $this->saveBackfillProgress($batchMinId);
-            }
-
-            $this->stdout(sprintf(
-                "第 %d 批完成:本批 %d 条,累计扫描 %d,需漏补 %d,写入关系 %d 行,跳过 %d,checkpoint id=%d\n",
-                $batchNo,
-                count($list),
-                $total,
-                $needBackfill,
-                $inserted,
-                $skipped,
-                (int)$batchMinId
-            ));
-
-            if ($this->clearId > 0 || count($list) < $fetchLimit) {
-                break;
-            }
-            $this->sleepBetweenBatch();
-        }
-
-        if (!$this->dryRun && $this->clearId <= 0 && $cursorId !== null) {
-            $this->stdout("进度已保存,下次从 id < {$cursorId} 继续\n");
-        }
-        $this->stdout(sprintf(
-            "全部完成 [%s]:扫描 %d 条 xhClear,需漏补 %d 条,写入 %d 行关系,跳过 %d 条\n",
-            $label,
-            $total,
-            $needBackfill,
-            $inserted,
-            $skipped
-        ));
-        if (!empty($styleStats)) {
-            ksort($styleStats);
-            foreach ($styleStats as $style => $stat) {
-                $this->stdout(sprintf(
-                    "  clearStyle=%d:扫描 %d,需漏补 %d,跳过 %d\n",
-                    $style,
-                    (int)$stat['scan'],
-                    (int)$stat['need'],
-                    (int)$stat['skip']
-                ));
-            }
-        }
-        return ExitCode::OK;
-    }
-
-    /**
-     * 按主键倒序轻量拉取一批 xhClear(只查回填所需字段,LIMIT 走主键索引)
-     */
-    private function fetchClearBatch(array $clearStyles, $cursorId, $limit)
-    {
-        $clearStyles = array_values(array_unique(array_filter(array_map('intval', $clearStyles))));
-        if (empty($clearStyles)) {
-            return [];
-        }
-        $inParts = [];
-        $params = [];
-        foreach ($clearStyles as $idx => $style) {
-            $key = ':s' . $idx;
-            $inParts[] = $key;
-            $params[$key] = $style;
-        }
-        $inSql = implode(',', $inParts);
-
-        if ($this->clearId > 0) {
-            $params[':id'] = intval($this->clearId);
-            $row = Yii::$app->db->createCommand(
-                'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
-                . ' WHERE id = :id AND clearStyle IN (' . $inSql . ') LIMIT 1'
-            )->bindValues($params)->queryOne();
-            return $row ? [$row] : [];
-        }
-
-        $sql = 'SELECT id, orderSn, saleIds, purchaseIds, status, clearStyle FROM ' . Clear::tableName()
-            . ' WHERE clearStyle IN (' . $inSql . ')';
-        if ($cursorId !== null) {
-            $sql .= ' AND id < :cursorId';
-            $params[':cursorId'] = intval($cursorId);
-        }
-        $sql .= ' ORDER BY id DESC LIMIT ' . intval($limit);
-        return Yii::$app->db->createCommand($sql)->bindValues($params)->queryAll();
-    }
-
-    private function sleepBetweenBatch()
-    {
-        if ($this->sleepMs > 0) {
-            usleep($this->sleepMs * 1000);
-        }
-    }
-
-    private function getBackfillProgressFile()
-    {
-        $key = $this->backfillProgressKey !== '' ? $this->backfillProgressKey : 'all';
-        return Yii::getAlias('@console/runtime/order_cg_clear_backfill_' . $key . '.last_id');
-    }
-
-    private function loadBackfillProgress()
-    {
-        $file = $this->getBackfillProgressFile();
-        if (!is_file($file)) {
-            return null;
-        }
-        $id = intval(trim((string)file_get_contents($file)));
-        return $id > 0 ? $id : null;
-    }
-
-    private function saveBackfillProgress($clearId)
-    {
-        if ($this->dryRun || $this->clearId > 0) {
-            return;
-        }
-        $clearId = intval($clearId);
-        if ($clearId <= 0) {
-            return;
-        }
-        $file = $this->getBackfillProgressFile();
-        $dir = dirname($file);
-        if (!is_dir($dir)) {
-            mkdir($dir, 0777, true);
-        }
-        file_put_contents($file, (string)$clearId);
-    }
-
-    private function clearBackfillProgress()
-    {
-        $file = $this->getBackfillProgressFile();
-        if (is_file($file)) {
-            unlink($file);
-        }
-    }
-
-    private function isCliOptionPassed($name)
-    {
-        foreach ($_SERVER['argv'] ?? [] as $arg) {
-            if ($arg === '--' . $name || strpos($arg, '--' . $name . '=') === 0) {
-                return true;
-            }
-        }
-        return false;
-    }
-
-}