Przeglądaj źródła

feat(api): 更新测试控制器实现1688商品分类追溯功能

- 新增 UserAddressRepository 导入
- 移除原有的测试代码和注释掉的功能代码
- 实现1688商品分类层级追溯功能,包括商品详情查询、分类ID追溯和顶级分类保存
- 添加数据库操作用于将追溯到的顶级分类保存到 store_category 表并更新商品分类ID
- 增加分步骤执行逻辑,包括读取本地商品、查询1688商品详情、追溯分类层级和保存分类数据
- 优化代码结构,移除过时的支付和退款相关测试代码
shichen 2 miesięcy temu
rodzic
commit
6dce613b02
1 zmienionych plików z 199 dodań i 265 usunięć
  1. 199 265
      app/controller/api/Test.php

+ 199 - 265
app/controller/api/Test.php

@@ -5,6 +5,7 @@ namespace app\controller\api;
5 5
 use app\common\enum\CommonEnum;
6 6
 use app\common\repositories\merchant\order\OrderMerchantRepository;
7 7
 use app\common\repositories\shared\SharedProsperityRecommendConfigRepository;
8
+use app\common\repositories\user\UserAddressRepository;
8 9
 use app\common\repositories\user\UserRepository;
9 10
 use app\services\ThirdParty\AlibabaAgent\OrderService;
10 11
 use app\services\ThirdParty\AlibabaAgent\ProductService;
@@ -34,282 +35,216 @@ class Test
34 35
      */
35 36
     public function test()
36 37
     {
37
-
38
-        $json = [
39
-            'created_time' => '1775884033',
40
-            'data' => [
41
-                'app_id' => 'app_44108546-d27a-48ee-88c1-84b45b75114f',
42
-                'business_mode' => '00',
43
-                'created_time' => '20260411130713',
44
-                'description' => '',
45
-                'end_time' => '20260411130724',
46
-                'expend' => [
47
-                    'buyer_logon_id' => '131****9459',
48
-                    'cashPayAmt' => '298.00',
49
-                    'open_id' => '2088702188085230',
50
-                    'sub_open_id' => '2088702188085230',
51
-                ],
52
-                'fee_amt' => '1.13',
53
-                'id' => '002212026041113071210888906215589441536',
54
-                'order_no' => 'ALI177588403255323243_466',
55
-                'out_trans_id' => '2026041123001485231459472633',
56
-                'party_order_id' => '02232604114723298914940',
57
-                'pay_amt' => '298.00',
58
-                'pay_channel' => 'alipay_pub',
59
-                'real_amt' => '298.00',
60
-                'status' => 'succeeded',
61
-                'trans_response_add_info' => [
62
-                    'fund_bill_list' => [
63
-                        [
64
-                            'amount' => '298.00',
65
-                            'fund_channel' => 'ALIPAYACCOUNT',
66
-                        ],
67
-                    ],
68
-                ],
69
-            ],
70
-            'prod_mode' => 'true',
71
-            'sign' => 'fgbSc95NQDor1/jH3/L0G55l3XB7wl+sDt45Mtig/8eSvLIVo0uoyyD+jWaLkXV5xY2iAV3w8W4tiyVUcMQwVvwDIt9zQ44HTo05ng0e6CHCXLxFQbg/SHsjmK/3hin/2t6HkEjlitJYVikcPxMA0vnlR+lL/xMOYqNMDuq9oQQ=',
72
-            'id' => '002210888906265044500480',
73
-            'type' => 'HF',
74
-            'app_id' => 'app_44108546-d27a-48ee-88c1-84b45b75114f',
75
-            'object' => 'payment',
76
-        ];
77
-
78
-        /** @var OrderMerchantRepository $orderMerchantRepository */
79
-        $orderMerchantRepository = app()->make(OrderMerchantRepository::class);
80
-        $res = $orderMerchantRepository->doNotifyHF($json['data']);
81
-
82
-        dd($res);
83
-
84
-        die;
85
-
86
-        $orderService = new OrderService();
87
-        //
88
-        //
89
-        // $orderId = '3298535043727138963';
90
-        // $payRes = $orderService->prepareProtocolPay(['orderId'=>$orderId]);
91
-        // dd($payRes);
92
-
93
-        $cargoParamList = '{"offerId":"1045816431082","specId":"2fc39c573acfab640d10bcb1b533f041","quantity":1}';
94
-        $addressParam = '{"fullName":"测试","mobile":"17756507016","provinceText":"河北省","cityText":"廊坊市","areaText":"三河市","address":"兴远高科产业园23号楼2层210"}';
95
-
96
-
97
-        $cargoParamList = json_decode($cargoParamList,true);
98
-        $addressParam = json_decode($addressParam,true);
99
-        $flow = 'general';
100
-
101
-        $res = $orderService->previewOrder(['cargoParamList' => $cargoParamList, 'addressParam' => $addressParam,'flow'=>$flow]);
102
-        dd($res);
103
-
104
-
105
-
106
-
107
-
108
-        /** @var SharedProsperityRecommendConfigRepository $sharedProsperityRecommendConfigRepository */
109
-        $sharedProsperityRecommendConfigRepository = app()->make(SharedProsperityRecommendConfigRepository::class);
110
-        // 共富配置--获取最大的直推奖比例
111
-        $sharedProsperityRecommendConfigEntityByMaxRewardRatio = $sharedProsperityRecommendConfigRepository->getSharedProsperityRecommendConfigEntityByMaxRewardRatio();
112
-        // 共富配置--获取最大的分享奖比例
113
-        $sharedProsperityRecommendConfigEntityByMaxShareRewardRatio = $sharedProsperityRecommendConfigRepository->getSharedProsperityRecommendConfigEntityByMaxShareRatio();
114
-        // 利润 减去 顶格的直推奖,剩下的是PV值
115
-        $sharPveRate = bcadd($sharedProsperityRecommendConfigEntityByMaxRewardRatio->getRewardRatio(),$sharedProsperityRecommendConfigEntityByMaxShareRewardRatio->getShareRatio(), CommonEnum::DECIMAL_PLACES_OF_THE_AMOUNT);
116
-        $pvProportion = bcsub('1', bcdiv($sharPveRate, '100', 4), 2);
117
-
118
-        dd($pvProportion);
119
-
120
-        $orderShareUid = 6;
121
-        $ShareUser = Db::name('shared_prosperity_user')->where(["user_id" => $orderShareUid])->find();
122
-        if ($ShareUser) {
123
-            $rate = Db::name('shared_prosperity_recommend_config')->where(["level" => $ShareUser['partner_level']])->value("share_ratio");
124
-            $rate = $rate / 100;
125
-        }else{
126
-            // 计算 佣金
127
-            $user_group_share_rate = Db::name("system_config_value")->where(["config_key" => "user_group_share_rate"])->value("value");
128
-            $user_group_share_rate = json_decode($user_group_share_rate, true);
129
-            $user_group_share_rate = array_column($user_group_share_rate, 'rate', 'user_groub');
130
-
131
-            /** @var UserRepository $userRepository */
132
-            $userRepository = app()->make(UserRepository::class);
133
-            $userEntityByShareUserEntity = $userRepository->getUserEntityByUid($orderShareUid);
134
-            $userGroup = $userEntityByShareUserEntity->getUserGroup();
135
-            $rate = ($user_group_share_rate[$userGroup] ?? 0) / 100;
136
-        }
137
-
138
-
139
-        dd($rate);
140
-
141
-
142
-        die;
143
-        $data = [
144
-            'orderId' => '123', // 1688订单号,接口里
145
-            'orderEntryIds' => '123',// 1688子订单号,接口里
146
-            'disputeRequest' => 'refund', // 单选
147
-            'description' => '不想要了', // 填写的
148
-            'applyPayment' => '4.82', // 退款金额,接口里
149
-            'applyCarriage' => '0', // 运费金额,接口里
150
-            'applyReasonId' => '20006', // 退款原因,选的
151
-            'goodsStatus' => 'refundWaitBuyerReceive', // 货物状态,接口里
152
-            'refund_order_id' => 33 // 列表的refund_order_id
153
-        ];
154
-
155
-        $orderService = new OrderService();
156
-
157
-        // 构建1688接口参数(前端 disputeRequest 映射为 1688 接口的 disputeReasonId)
158
-        $params = [
159
-            'orderId'         => (string)$data['orderId'],
160
-            'orderEntryIds'   => $data['orderEntryIds'],
161
-            'disputeReasonId' => (string)$data['disputeRequest'],
162
-            'description'     => (string)$data['description'],
163
-            'applyPayment'    => (string)$data['applyPayment'] * 100,
164
-            'applyCarriage'   => (string)$data['applyCarriage'] * 100,
165
-            'applyReasonId'   => (string)$data['applyReasonId'],
166
-            'goodsStatus'     => (string)$data['goodsStatus'],
167
-        ];
168
-
169
-        // 调用1688 API提交售后申请
170
-        $result = $orderService->createRefund($params);
171
-
172
-        // 记录到 store_refund_alibaba 表(不管成功与否都保存原始数据)
173
-        $insertData = [
174
-            'refund_order_id'   => (int)($data['refund_order_id'] ?? 0),
175
-            'alibaba_order_id'  => (string)$data['orderId'],
176
-            'order_entry_ids'   => $data['orderEntryIds'],
177
-            'dispute_reason_id' => (string)$data['disputeRequest'],
178
-            'description'       => (string)$data['description'],
179
-            'goods_status'      => (string)$data['goodsStatus'],
180
-            'apply_payment'     => (string)$data['applyPayment'],
181
-            'apply_carriage'    => (string)$data['applyCarriage'],
182
-            'result_data'       => json_encode($result['rawData'] ?? [], JSON_UNESCAPED_UNICODE),
183
-        ];
184
-
185
-        if ($result['success']) {
186
-            // 提交成功
187
-            $insertData['status'] = 1;
188
-            $insertData['alibaba_refund_id'] = $result['refundId'] ?? '';
189
-            $insertData['alibaba_status'] = $result['status'] ?? '';
190
-            Db::name('store_refund_alibaba')->insert($insertData);
191
-
192
-            // 更新退款单的 after_sn 字段为1688售后单ID
193
-            if (!empty($data['refund_order_id']) && !empty($result['refundId'])) {
194
-                Db::name('store_refund_order')
195
-                    ->where('refund_order_id', (int)$data['refund_order_id'])
196
-                    ->update(['after_sn' => $result['refundId']]);
38
+        // ============================================================
39
+        // 功能:从本地 store_product 表读取 is_alibaba=1 的商品
40
+        //       → 根据 spu_id(1688商品ID)查询1688商品详情
41
+        //       → 获取分类ID → 重复调用1688分类接口向上追溯
42
+        //       → 直到 parentIDs=[0](顶级分类)
43
+        //       → 将顶级分类保存到 store_category 表(按 alibaba_cate_id 去重)
44
+        //       → 更新商品的 cate_id
45
+        // ============================================================
46
+        try {
47
+            /** @var ProductService $productService */
48
+            $productService = app()->make(ProductService::class);
49
+            $productService->setAccessToken('ce15fc70-b462-43bf-acc3-f87e43c858ba');
50
+
51
+            // ============================================================
52
+            // 第一步:从 store_product 表读取 is_alibaba=1 的商品
53
+            // ============================================================
54
+            echo "========== 第一步:读取本地1688商品列表 ==========\n";
55
+
56
+            $productList = Db::name('store_product')
57
+                ->where('is_alibaba', 1)
58
+                ->where('cate_id', 0)
59
+                ->where('is_del', 0)
60
+                ->field('product_id, store_name, spu_id, image, price, is_alibaba')
61
+                ->limit(50)
62
+                ->select()
63
+                ->toArray();
64
+
65
+            if (empty($productList)) {
66
+                echo "没有找到 is_alibaba=1 的商品\n";
67
+                die;
197 68
             }
198 69
 
199
-            return app('json')->success([
200
-                'alibaba_refund_id' => $result['refundId'] ?? '',
201
-                'alibaba_status'    => $result['status'] ?? '',
202
-            ], '提交1688售后申请成功');
203
-        } else {
204
-            // 提交失败
205
-            $insertData['status'] = 2;
206
-            $insertData['fail_message'] = $result['status'] ?? '1688接口调用失败';
207
-            Db::name('store_refund_alibaba')->insert($insertData);
208
-            return app('json')->fail($result['status'] ?? '提交1688售后申请失败');
209
-        }
210
-
211
-        // $alibabaOrderId = '3300284931845138963';
212
-
213
-        // $orderService = new OrderService();
214
-        // $result = $orderService->getRefundReasonList(['orderId' => $alibabaOrderId]);
215
-
216
-// dd($result);
217
-
218
-        die;
219
-
220
-        // $id = $this->request->params(['pid'])['pid'];
221
-        $id = request()->params(['pid'])['pid'];
222
-        if (!$id) {
223
-            return app('json')->fail('参数不正确');
224
-        }
225
-
226
-
227
-
228
-
229
-
230
-
231
-
232
-
233
-
234
-
235
-
236
-
237
-
238
-
239
-
240
-
241
-
242
-
243
-
244
-
245
-
246
-
247
-
248
-        dd(request());
249
-        $appid = 'wx9082e5ac2fdb513f';
250
-        $sessionKey =str_replace(' ','+', 'AIXeWyu4hRRg0EkD8Z23JA==');
251
-        $encryptedData=str_replace(' ','+','7OCmD5\/4xylVdxYswuTrA6TKzmXNkDymIpdyx9GZIBS+qCIcsBpUnJ5U5GXOTn0JvfQYic9e+0idCTP7QJyJkjjlGWNwwiE0\/WnhBvhAWYlo+Hkh+v3ioiSvqJ7zC4bEJ3GWDNyts5fEX\/u+tL25DySDuUoDoCJs6k+ThlVO5NiecPIcgnmfrLG6nV4Xh3y9H6p\/loj71LRJ47hywX9OQg==');
252
-        $iv =str_replace(' ','+', 'NbjIV0k1DyDWxU7JSSF44w==');
253
-        $pc = new WXBizDataCrypt($appid, $sessionKey);
254
-        $errCode = $pc->decryptData($encryptedData, $iv, $data );
255
-dd($errCode);
256
-        die;
257
-
258
-
259
-
260
-
261
-
262
-
263
-
264
-
265
-
266
-
267
-
268
-
269
-
270
-
271
-
272
-
70
+            echo "共找到 " . count($productList) . " 个1688商品\n\n";
273 71
 
72
+            foreach ($productList as $i => $product) {
73
+                echo ($i + 1) . ". {$product['store_name']}\n";
74
+                echo "   本地商品ID: {$product['product_id']}\n";
75
+                echo "   1688商品ID(spu_id): {$product['spu_id']}\n";
76
+                echo "   价格: ¥{$product['price']}\n\n";
77
+            }
274 78
 
79
+            // ============================================================
80
+            // 第二步+第三步+第四步:遍历商品,查询详情 → 追溯分类层级 → 保存顶级分类
81
+            // ============================================================
82
+            echo "========== 第二步:查询1688商品详情,获取分类ID ==========\n\n";
275 83
 
84
+            foreach ($productList as $product) {
85
+                $spuId = $product['spu_id'];
86
+                $productId = $product['product_id'];
87
+                $storeName = $product['store_name'];
276 88
 
89
+                if (empty($spuId)) {
90
+                    echo "商品 {$productId} 的 spu_id 为空,跳过\n\n";
91
+                    continue;
92
+                }
277 93
 
278
-        die;
279
-        // ============================================================
280
-        // 通过 ProductService 调用 1688 分销商品列表
281
-        // ============================================================
282
-        try {
283
-            /** @var ProductService $productService */
284
-            $productService = app()->make(ProductService::class);
94
+                echo "--- 查询商品: {$storeName} (spu_id: {$spuId}) ---\n";
285 95
 
286
-            // 设置 access_token(由用户提供或通过OAuth获取)
287
-            $productService->setAccessToken('dc8eab20-f10f-4688-9e45-9ebfa182c7c2');
96
+                // ---- 第二步:获取商品详情,提取分类ID ----
97
+                $detail = $productService->getProductDetail($spuId);
288 98
 
289
-            // 搜索参数
290
-            $params = [
291
-                'page'     => 1,      // 页码
292
-                'limit'    => 50,     // 每页条数(最大50)
293
-            ];
99
+                if ($detail === false || empty($detail)) {
100
+                    echo "   获取1688商品详情失败\n\n";
101
+                    continue;
102
+                }
294 103
 
295
-            $result = $productService->searchProducts($params);
104
+                $categoryId = $detail['categoryId'] ?? 0;
105
+                $categoryName = $detail['categoryName'] ?? '';
106
+
107
+                echo "   商品标题: {$detail['title']}\n";
108
+                echo "   分类ID: {$categoryId}\n";
109
+                echo "   分类名称: {$categoryName}\n";
110
+                echo "   价格区间: ¥{$detail['minPrice']} ~ ¥{$detail['maxPrice']}\n\n";
111
+
112
+                // ---- 第三步:追溯完整分类层级(直到顶级分类) ----
113
+                echo "========== 第三步:追溯完整分类层级(直到顶级分类) ==========\n";
114
+
115
+                $categoryPath = []; // 从叶子到根的顺序存储
116
+                $categoryPathReversed = []; // 从根到叶子的顺序
117
+
118
+                if (!empty($categoryId)) {
119
+                    $currentCategoryId = $categoryId;
120
+                    $maxLevels = 10;
121
+                    $level = 0;
122
+
123
+                    while ($currentCategoryId > 0 && $level < $maxLevels) {
124
+                        $level++;
125
+                        echo "  第{$level}层: 查询分类ID [{$currentCategoryId}]...\n";
126
+
127
+                        $categoryInfoList = $productService->getCategories((string)$currentCategoryId);
128
+
129
+                        if ($categoryInfoList === false || empty($categoryInfoList)) {
130
+                            echo "   分类ID [{$currentCategoryId}] 查询失败或无数据,停止追溯\n";
131
+                            break;
132
+                        }
133
+
134
+                        // 查找与当前分类ID匹配的分类信息
135
+                        $currentCategoryInfo = null;
136
+                        foreach ($categoryInfoList as $cat) {
137
+                            if (($cat['categoryID'] ?? 0) == $currentCategoryId) {
138
+                                $currentCategoryInfo = $cat;
139
+                                break;
140
+                            }
141
+                        }
142
+
143
+                        if ($currentCategoryInfo === null) {
144
+                            $currentCategoryInfo = $categoryInfoList[0] ?? null;
145
+                        }
146
+
147
+                        if ($currentCategoryInfo === null) {
148
+                            echo "   无法获取分类信息,停止追溯\n";
149
+                            break;
150
+                        }
151
+
152
+                        $catId = $currentCategoryInfo['categoryID'] ?? 0;
153
+                        $catName = $currentCategoryInfo['name'] ?? '';
154
+                        $parentIDs = $currentCategoryInfo['parentIDs'] ?? [];
155
+                        $isLeaf = $currentCategoryInfo['isLeaf'] ?? false;
156
+
157
+                        $categoryPath[] = [
158
+                            'category_id'   => $catId,
159
+                            'category_name' => $catName,
160
+                            'is_leaf'       => $isLeaf,
161
+                            'parent_ids'    => $parentIDs,
162
+                        ];
163
+
164
+                        echo "   当前分类: [{$catId}] {$catName}, parentIDs: [" . implode(',', $parentIDs) . "], isLeaf: " . ($isLeaf ? '是' : '否') . "\n";
165
+
166
+                        if (empty($parentIDs) || in_array(0, $parentIDs, true) || in_array('0', $parentIDs, true)) {
167
+                            echo "   → 已到达顶级分类,追溯完成\n";
168
+                            break;
169
+                        }
170
+
171
+                        $currentCategoryId = (int)$parentIDs[0];
172
+                    }
173
+
174
+                    if ($level >= $maxLevels) {
175
+                        echo "   警告:达到最大追溯层数 {$maxLevels},可能存在循环\n";
176
+                    }
177
+
178
+                    // 输出完整分类层级(从顶级到叶子)
179
+                    $categoryPathReversed = array_reverse($categoryPath);
180
+                    $pathStr = '';
181
+                    foreach ($categoryPathReversed as $i => $cat) {
182
+                        if ($i > 0) $pathStr .= ' → ';
183
+                        $pathStr .= "[{$cat['category_id']}] {$cat['category_name']}";
184
+                    }
185
+                    echo "\n   完整分类层级: {$pathStr}\n\n";
186
+
187
+                } else {
188
+                    echo "   分类ID为空,无法追溯分类层级\n\n";
189
+                }
296 190
 
297
-            if ($result === false) {
298
-                echo "请求失败,请查看日志获取详细信息。\n";
299
-            } else {
300
-                echo "=== 1688分销商品列表 ===\n";
301
-                echo "总数: {$result['total']}\n";
302
-                echo "页码: {$result['page']}\n";
303
-                echo "每页: {$result['pageSize']}\n";
304
-                echo "商品数: " . count($result['list']) . "\n\n";
305
-
306
-                foreach ($result['list'] as $i => $product) {
307
-                    echo ($i + 1) . ". {$product['title']}\n";
308
-                    echo "   商品ID: {$product['productId']}\n";
309
-                    echo "   价格: ¥{$product['minPrice']} ~ ¥{$product['maxPrice']}\n";
310
-                    echo "   月销: {$product['monthSales']}\n";
311
-                    echo "   主图: {$product['mainImage']}\n\n";
191
+                // ---- 第四步:将顶级分类保存到 store_category 表,并更新商品 cate_id ----
192
+                echo "========== 第四步:保存顶级分类到 store_category 表 ==========\n";
193
+
194
+                if (!empty($categoryPathReversed)) {
195
+                    $topCategory = $categoryPathReversed[0];
196
+                    $alibabaCateId = $topCategory['category_id'];
197
+                    $alibabaCateName = $topCategory['category_name'];
198
+
199
+                    echo "  顶级分类: [{$alibabaCateId}] {$alibabaCateName}\n";
200
+
201
+                    // 按 alibaba_cate_id 查重
202
+                    $existingCategory = Db::name('store_category')
203
+                        ->where('alibaba_cate_id', $alibabaCateId)
204
+                        ->find();
205
+
206
+                    if ($existingCategory) {
207
+                        $storeCategoryId = $existingCategory['store_category_id'];
208
+                        echo "  分类已存在 (store_category_id: {$storeCategoryId}),跳过创建\n";
209
+                    } else {
210
+                        $insertData = [
211
+                            'pid'             => 564,
212
+                            'cate_name'       => $alibabaCateName,
213
+                            'path'            => '',
214
+                            'sort'            => 0,
215
+                            'pic'             => '',
216
+                            'is_show'         => 1,
217
+                            'level'           => 2,
218
+                            'mer_id'          => 0,
219
+                            'create_time'     => date('Y-m-d H:i:s'),
220
+                            'alibaba_cate_id' => $alibabaCateId,
221
+                        ];
222
+
223
+                        $storeCategoryId = Db::name('store_category')->insertGetId($insertData);
224
+
225
+                        if ($storeCategoryId) {
226
+                            $path = '/563/564/';
227
+                            Db::name('store_category')
228
+                                ->where('store_category_id', $storeCategoryId)
229
+                                ->update(['path' => $path]);
230
+                            echo "  顶级分类创建成功! store_category_id: {$storeCategoryId}, path: {$path}\n";
231
+                        } else {
232
+                            echo "  顶级分类创建失败\n";
233
+                        }
234
+                    }
235
+
236
+                    // 更新商品 cate_id
237
+                    if (!empty($storeCategoryId)) {
238
+                        Db::name('store_product')
239
+                            ->where('product_id', $productId)
240
+                            ->update(['cate_id' => $storeCategoryId]);
241
+                        echo "  已更新商品(product_id: {$productId}) 的 cate_id 为 {$storeCategoryId}\n";
242
+                    }
243
+                } else {
244
+                    echo "  未找到顶级分类数据\n";
312 245
                 }
246
+
247
+                echo "\n";
313 248
             }
314 249
 
315 250
         } catch (\Throwable $e) {
@@ -325,7 +260,6 @@ dd($errCode);
325 260
 
326 261
 
327 262
 
328
-
329 263
         $sessionKey = request()->post(['sessionKey']);
330 264
         $encryptedData = request()->post(['encryptedData']);
331 265
         $iv = request()->post(['iv']);