AlibabaTodayImport.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. namespace app\command;
  3. use app\common\repositories\store\product\ProductRepository;
  4. use app\services\ThirdParty\AlibabaAgent\ProductService;
  5. use think\console\Command;
  6. use think\console\Input;
  7. use think\console\Output;
  8. use think\facade\Db;
  9. /**
  10. * 今日1688商品自动入库命令
  11. *
  12. * 从 alibaba_import_goods 表中获取今日创建的商品,
  13. * 调用 ProductService::importToStoreProduct() 进行正式入库到 store_product 表,
  14. * 然后通过 ProductRepository::update() 更新原价和分润设置
  15. *
  16. * 用法:
  17. * php think alibaba:today-import # 默认今天,mer_id=3447
  18. * php think alibaba:today-import --mer_id=3447 # 指定商户ID
  19. * php think alibaba:today-import --date=2026-05-21 # 指定日期
  20. * php think alibaba:today-import --mer_id=3447 --date=2026-05-21 # 指定商户+日期
  21. * php think alibaba:today-import --batch=100 # 每批处理100条(默认50)
  22. * php think alibaba:today-import --skip=10 # 跳过前10条(断点续传)
  23. * php think alibaba:today-import --limit=5 # 只处理5条(不设置则全部处理)
  24. *
  25. * 定时任务配置(每天23:55执行):
  26. * 55 23 * * * php /www/wwwroot/shop/think alibaba:today-import --mer_id=3447 >> /tmp/alibaba_today_import.log 2>&1
  27. *
  28. * 分润设置(写死):
  29. * - extension_type: 1(开启分润)
  30. * - concession_pri: 售价 × 15%(商家让利金额)
  31. * - extension_one: 15(SKU级分润比例)
  32. * - commission: 保持原样(不修改)
  33. *
  34. * 原价计算规则(根据SKU售价阶梯加价):
  35. * 1-20元 => 固定加5元
  36. * 21-50元 => 固定加20元
  37. * 51-120元 => 固定加40元
  38. * 121-200元 => 固定加45元
  39. * 201元以上 => 固定加50元
  40. */
  41. class AlibabaTodayImport extends Command
  42. {
  43. protected function configure()
  44. {
  45. $this->setName('alibaba:today-import')
  46. ->setDescription('从alibaba_import_goods获取今日创建的商品,调用importStore接口正式入库')
  47. ->addOption('mer_id', null, \think\console\input\Option::VALUE_OPTIONAL, '商户ID', '3447')
  48. ->addOption('date', null, \think\console\input\Option::VALUE_OPTIONAL, '指定日期 (Y-m-d),默认今天', '')
  49. ->addOption('batch', null, \think\console\input\Option::VALUE_OPTIONAL, '每批处理数量', '50')
  50. ->addOption('skip', null, \think\console\input\Option::VALUE_OPTIONAL, '跳过前N条(断点续传)', '0')
  51. ->addOption('limit', null, \think\console\input\Option::VALUE_OPTIONAL, '限制处理条数,不设置则全部处理', '0');
  52. }
  53. protected function execute(Input $input, Output $output)
  54. {
  55. // 解除时间限制
  56. set_time_limit(0);
  57. $output->writeln('========================================');
  58. $output->writeln(' 1688今日商品自动入库 开始');
  59. $output->writeln('========================================');
  60. // 1. 解析参数
  61. $merId = (int)$input->getOption('mer_id');
  62. $date = $input->getOption('date');
  63. $batch = (int)$input->getOption('batch');
  64. $skip = (int)$input->getOption('skip');
  65. $limit = (int)$input->getOption('limit');
  66. if ($batch < 1) $batch = 50;
  67. if ($skip < 0) $skip = 0;
  68. if ($limit < 0) $limit = 0;
  69. if (empty($date)) {
  70. $date = date('Y-m-d');
  71. }
  72. // ============================================================
  73. // 分润配置(写死)
  74. // ============================================================
  75. $profitConfig = [
  76. 'extension_type' => 1, // 1=开启分润
  77. 'concession_rate' => 0.15, // 商家让利比例15%(concession_pri = 售价 × 15%)
  78. 'extension_one' => 15, // SKU级分润比例15%
  79. ];
  80. $output->writeln("商户ID: {$merId}");
  81. $output->writeln("查询日期: {$date}");
  82. $output->writeln("每批数量: {$batch}");
  83. $output->writeln("跳过前N条: {$skip}");
  84. $output->writeln("限制条数: " . ($limit > 0 ? $limit : '不限制'));
  85. $output->writeln('分润设置:');
  86. $output->writeln(" extension_type: {$profitConfig['extension_type']} (开启分润)");
  87. $output->writeln(" concession_rate: {$profitConfig['concession_rate']} (售价×{$profitConfig['concession_rate']})");
  88. $output->writeln(" extension_one: {$profitConfig['extension_one']}%");
  89. // 2. 查询今日创建的 alibaba_import_goods 记录(只查ID,不查全字段,节省内存)
  90. $todayStart = $date . ' 00:00:00';
  91. $todayEnd = $date . ' 23:59:59';
  92. $output->write('正在查询今日待入库商品... ');
  93. $query = Db::name('alibaba_import_goods')
  94. ->where('status', 1)
  95. ->where('create_time', '>=', $todayStart)
  96. ->where('create_time', '<=', $todayEnd)
  97. ->order('id', 'ASC');
  98. // 如果设置了 limit,则限制查询数量
  99. if ($limit > 0) {
  100. $query->limit($limit);
  101. }
  102. $allIds = $query->column('id');
  103. $total = count($allIds);
  104. $output->writeln("共 {$total} 条");
  105. if ($total === 0) {
  106. $output->writeln("{$date} 没有需要入库的商品");
  107. $output->writeln('========================================');
  108. $output->writeln(' 1688今日商品自动入库 结束 (无商品)');
  109. $output->writeln('========================================');
  110. return;
  111. }
  112. // 3. 应用 skip 跳过已处理的
  113. if ($skip > 0) {
  114. $allIds = array_slice($allIds, $skip);
  115. $output->writeln("跳过前 {$skip} 条,剩余 " . count($allIds) . " 条");
  116. }
  117. // 4. 分批处理
  118. /** @var ProductService $productService */
  119. $productService = app()->make(ProductService::class);
  120. $chunks = array_chunk($allIds, $batch);
  121. $totalChunks = count($chunks);
  122. $output->writeln("共分 {$totalChunks} 批执行");
  123. $output->writeln('');
  124. $globalSuccess = 0;
  125. $globalFail = 0;
  126. $globalProfitSet = 0;
  127. $startTime = time();
  128. foreach ($chunks as $chunkIndex => $idBatch) {
  129. $batchStartTime = time();
  130. $batchNum = $chunkIndex + 1;
  131. $processedCount = $skip + ($chunkIndex * $batch) + 1;
  132. $output->writeln("--- 第 {$batchNum}/{$totalChunks} 批 (已处理 {$processedCount}/{$total}) ---");
  133. foreach ($idBatch as $importId) {
  134. $output->write(" [{$processedCount}/{$total}] import_goods_id={$importId} ... ");
  135. try {
  136. // 4a. 调用原始入库方法
  137. $result = $productService->importToStoreProduct($importId, $merId);
  138. if ($result['code'] === 200) {
  139. $productId = $result['product_id'];
  140. $globalSuccess++;
  141. // 4b. 组装数据,调用 ProductRepository::update() 更新原价和分润
  142. try {
  143. self::updateProductData($productId, $merId, $profitConfig);
  144. $globalProfitSet++;
  145. $output->write("<info>[原价+分润已更新]</info> ");
  146. } catch (\Throwable $updateE) {
  147. $output->write("<comment>[更新失败: {$updateE->getMessage()}]</comment> ");
  148. }
  149. $output->writeln("<info>成功 => product_id={$productId}</info>");
  150. } else {
  151. $globalFail++;
  152. $output->writeln("<comment>跳过: {$result['msg']}</comment>");
  153. }
  154. } catch (\Throwable $e) {
  155. $globalFail++;
  156. $output->writeln("<error>异常: {$e->getMessage()}</error>");
  157. }
  158. $processedCount++;
  159. }
  160. // 每批结束后输出当前进度和耗时
  161. $batchElapsed = time() - $batchStartTime;
  162. $totalElapsed = time() - $startTime;
  163. $output->writeln(" 本批耗时: {$batchElapsed}s | 累计耗时: {$totalElapsed}s | 累计成功: {$globalSuccess} | 累计失败: {$globalFail} | 更新: {$globalProfitSet}");
  164. $output->writeln('');
  165. // 每批之间短暂休眠,避免数据库压力过大
  166. if ($chunkIndex < $totalChunks - 1) {
  167. $output->writeln(" 等待 1 秒后继续下一批...");
  168. sleep(1);
  169. }
  170. }
  171. // 5. 输出汇总结果
  172. $totalElapsed = time() - $startTime;
  173. $output->writeln('');
  174. $output->writeln('========================================');
  175. $output->writeln(' 入库完成');
  176. $output->writeln('========================================');
  177. $output->writeln("总耗时: {$totalElapsed}s");
  178. $output->writeln("总处理: {$total} 条");
  179. $output->writeln("成功: {$globalSuccess} 条");
  180. $output->writeln("失败: {$globalFail} 条");
  181. $output->writeln("已更新原价+分润: {$globalProfitSet} 条");
  182. if ($globalFail > 0) {
  183. $output->writeln('');
  184. $output->writeln('<comment>提示: 失败的商品可以查看 alibaba 日志通道获取详细信息</comment>');
  185. $output->writeln("<comment> 重跑时可加 --skip={$skip} 跳过已处理的商品</comment>");
  186. }
  187. $output->writeln('========================================');
  188. $output->writeln(' 1688今日商品自动入库 结束');
  189. $output->writeln('========================================');
  190. }
  191. /**
  192. * 组装数据并调用 ProductRepository::update() 更新商品
  193. *
  194. * 从数据库查询商品完整信息,组装成 update 接口所需的格式,
  195. * 修改 ot_price(按阶梯计算)和 extension_one(15),
  196. * 然后调用 ProductRepository::update() 执行更新。
  197. *
  198. * @param int $productId
  199. * @param int $merId
  200. * @param array $profitConfig
  201. * @throws \Throwable
  202. */
  203. protected static function updateProductData(int $productId, int $merId, array $profitConfig): void
  204. {
  205. // 1. 查询 store_product 表获取商品基本信息
  206. $product = Db::name('store_product')
  207. ->where('product_id', $productId)
  208. ->find();
  209. if (!$product) {
  210. throw new \RuntimeException("商品不存在 product_id={$productId}");
  211. }
  212. // 2. 查询 store_product_attr_value 表获取所有SKU
  213. $skuValues = Db::name('store_product_attr_value')
  214. ->where('product_id', $productId)
  215. ->select()
  216. ->toArray();
  217. if (empty($skuValues)) {
  218. throw new \RuntimeException("商品SKU数据为空 product_id={$productId}");
  219. }
  220. // 3. 查询 store_product_attr 表获取规格属性
  221. $attrList = Db::name('store_product_attr')
  222. ->where('product_id', $productId)
  223. ->select()
  224. ->toArray();
  225. // 4. 查询 store_product_content 表获取商品详情
  226. $content = Db::name('store_product_content')
  227. ->where('product_id', $productId)
  228. ->value('content');
  229. // 5. 组装 attrValue 数据(参考 detail 接口返回格式)
  230. $attrValue = [];
  231. $skuPrices = [];
  232. foreach ($skuValues as $sku) {
  233. $salePrice = (float)$sku['price'];
  234. $skuPrices[] = $salePrice;
  235. // 根据售价区间计算原价
  236. $otPrice = self::calcOtPrice($salePrice);
  237. // detail 字段(规格明细)
  238. $detail = [];
  239. if (!empty($sku['detail'])) {
  240. $detail = is_string($sku['detail']) ? json_decode($sku['detail'], true) : $sku['detail'];
  241. }
  242. $attrValue[] = [
  243. 'product_id' => $productId,
  244. 'detail' => $detail,
  245. 'sku' => $sku['sku'] ?? '',
  246. 'stock' => $sku['stock'] ?? 0,
  247. 'sales' => $sku['sales'] ?? 0,
  248. 'image' => $sku['image'] ?? '',
  249. 'bar_code' => $sku['bar_code'] ?? '',
  250. 'cost' => (string)($sku['cost'] ?? 0),
  251. 'ot_price' => (string)$otPrice,
  252. 'price' => (string)($sku['price'] ?? 0),
  253. 'volume' => (string)($sku['volume'] ?? 0),
  254. 'weight' => (string)($sku['weight'] ?? 0),
  255. 'type' => $sku['type'] ?? 0,
  256. 'extension_one' => (string)$profitConfig['extension_one'],
  257. 'extension_two' => $sku['extension_two'] ?? null,
  258. 'unique' => $sku['unique'] ?? '',
  259. 'dacang_price' => (string)($sku['dacang_price'] ?? 0),
  260. 'cost_price' => $sku['cost_price'] ?? null,
  261. 'gong_sku_id' => $sku['gong_sku_id'] ?? null,
  262. 'gong_mer_profit' => (string)($sku['gong_mer_profit'] ?? 0),
  263. 'gong_pension' => $sku['gong_pension'] ?? null,
  264. 'gong_market_price'=> (string)($sku['gong_market_price'] ?? 0),
  265. 'plate_mer_profit' => (string)($sku['plate_mer_profit'] ?? 0),
  266. 'pension_num' => (string)($sku['pension_num'] ?? 0),
  267. 'share_num' => (string)($sku['share_num'] ?? 0),
  268. 'stock_num' => (string)($sku['stock_num'] ?? 0),
  269. 'shares_num' => (string)($sku['shares_num'] ?? 0),
  270. 'is_usable' => $sku['is_usable'] ?? 0,
  271. 'sku_id' => $sku['sku_id'] ?? '',
  272. 'spec_id' => $sku['spec_id'] ?? '',
  273. 'value0' => $sku['value0'] ?? ($sku['sku'] ?? ''),
  274. 'dacang_cost_price'=> (string)($sku['dacang_cost_price'] ?? 0),
  275. 'no_dacang_cost_price'=> (string)($sku['no_dacang_cost_price'] ?? 0),
  276. ];
  277. }
  278. // 6. 组装 attr 数据(规格属性)
  279. $attr = [];
  280. foreach ($attrList as $attrItem) {
  281. $detail = !empty($attrItem['attr_values'])
  282. ? explode('-!-', $attrItem['attr_values'])
  283. : [];
  284. $attr[] = [
  285. 'value' => $attrItem['attr_name'],
  286. 'detail' => $detail,
  287. ];
  288. }
  289. // 7. 计算商品级价格
  290. $minPrice = !empty($skuPrices) ? min($skuPrices) : 0;
  291. $maxOtPrice = self::calcOtPrice($minPrice);
  292. // 取所有SKU中最大的ot_price
  293. foreach ($skuPrices as $p) {
  294. $ot = self::calcOtPrice($p);
  295. if ($ot > $maxOtPrice) {
  296. $maxOtPrice = $ot;
  297. }
  298. }
  299. // 8. 组装完整数据(参考 detail 接口返回 + update 接口所需字段)
  300. $sliderImages = !empty($product['slider_image'])
  301. ? (is_string($product['slider_image']) ? explode(',', $product['slider_image']) : $product['slider_image'])
  302. : [];
  303. $updateData = [
  304. 'volunteer' => $product['volunteer'] ?? 0,
  305. 'image' => $product['image'] ?? '',
  306. 'slider_image' => $sliderImages,
  307. 'store_name' => $product['store_name'] ?? '',
  308. 'store_info' => $product['store_info'] ?? '',
  309. 'keyword' => $product['keyword'] ?? '',
  310. 'brand_id' => $product['brand_id'] ?? null,
  311. 'cate_id' => $product['cate_id'] ?? 0,
  312. 'mer_cate_id' => [], // 商户分类,保持空数组
  313. 'unit_name' => $product['unit_name'] ?? '件',
  314. 'sort' => $product['sort'] ?? 0,
  315. 'is_good' => $product['is_good'] ?? 0,
  316. 'temp_id' => $product['temp_id'] ?? 0,
  317. 'attr' => $attr,
  318. 'content' => $content ?? '',
  319. 'spec_type' => $product['spec_type'] ?? 1,
  320. 'extension_type' => $profitConfig['extension_type'],
  321. 'give_coupon_ids' => [],
  322. 'is_gift_bag' => $product['is_gift_bag'] ?? 0,
  323. 'type' => $product['type'] ?? 1,
  324. 'commission' => $product['commission'] ?? '',
  325. 'pension' => (string)($product['pension'] ?? '0.00'),
  326. 'pension_is' => $product['pension_is'] ?? 0,
  327. 'share_is' => $product['share_is'] ?? 0,
  328. 'ficti' => $product['ficti'] ?? 0,
  329. 'icon_type' => !empty($product['icon_type'])
  330. ? (is_string($product['icon_type']) ? json_decode($product['icon_type'], true) : $product['icon_type'])
  331. : [],
  332. 'attrValue' => $attrValue,
  333. ];
  334. // 9. 调用 ProductRepository::update() 执行更新
  335. /** @var ProductRepository $productRepository */
  336. $productRepository = app()->make(ProductRepository::class);
  337. $productRepository->update($productId, $updateData, $merId);
  338. }
  339. /**
  340. * 根据售价计算原价(阶梯加价)
  341. *
  342. * @param float $salePrice SKU售价
  343. * @return float 计算后的原价
  344. */
  345. protected static function calcOtPrice(float $salePrice): float
  346. {
  347. if ($salePrice <= 0) {
  348. return 0;
  349. }
  350. if ($salePrice >= 1 && $salePrice <= 20) {
  351. return $salePrice + 5;
  352. } elseif ($salePrice >= 21 && $salePrice <= 50) {
  353. return $salePrice + 20;
  354. } elseif ($salePrice >= 51 && $salePrice <= 120) {
  355. return $salePrice + 40;
  356. } elseif ($salePrice >= 121 && $salePrice <= 200) {
  357. return $salePrice + 45;
  358. } else {
  359. // 201元以上(含201-300及超过300),统一加50元
  360. return $salePrice + 50;
  361. }
  362. }
  363. }